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);
538 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
540 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
541 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
542 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
543 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
544 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
546 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
548 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
549 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
551 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
552 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
554 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
555 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
556 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
557 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
558 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
560 // Share the Altivec comparison restrictions.
561 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
562 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
563 setCondCodeAction(ISD::SETUGT, MVT::v2f64, Expand);
564 setCondCodeAction(ISD::SETUGE, MVT::v2f64, Expand);
565 setCondCodeAction(ISD::SETULT, MVT::v2f64, Expand);
566 setCondCodeAction(ISD::SETULE, MVT::v2f64, Expand);
568 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
569 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
571 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
572 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
574 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
576 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
578 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
579 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
581 // VSX v2i64 only supports non-arithmetic operations.
582 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
583 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
585 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
586 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
587 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
589 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
591 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
592 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
593 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
594 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
596 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
598 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
599 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
600 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
601 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
603 // Vector operation legalization checks the result type of
604 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
605 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
606 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
607 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
608 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
610 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
614 if (Subtarget->has64BitSupport()) {
615 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
616 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
619 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
620 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
621 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
622 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
624 setBooleanContents(ZeroOrOneBooleanContent);
625 // Altivec instructions set fields to all zeros or all ones.
626 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
629 setStackPointerRegisterToSaveRestore(PPC::X1);
630 setExceptionPointerRegister(PPC::X3);
631 setExceptionSelectorRegister(PPC::X4);
633 setStackPointerRegisterToSaveRestore(PPC::R1);
634 setExceptionPointerRegister(PPC::R3);
635 setExceptionSelectorRegister(PPC::R4);
638 // We have target-specific dag combine patterns for the following nodes:
639 setTargetDAGCombine(ISD::SINT_TO_FP);
640 setTargetDAGCombine(ISD::LOAD);
641 setTargetDAGCombine(ISD::STORE);
642 setTargetDAGCombine(ISD::BR_CC);
643 if (Subtarget->useCRBits())
644 setTargetDAGCombine(ISD::BRCOND);
645 setTargetDAGCombine(ISD::BSWAP);
646 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
648 setTargetDAGCombine(ISD::SIGN_EXTEND);
649 setTargetDAGCombine(ISD::ZERO_EXTEND);
650 setTargetDAGCombine(ISD::ANY_EXTEND);
652 if (Subtarget->useCRBits()) {
653 setTargetDAGCombine(ISD::TRUNCATE);
654 setTargetDAGCombine(ISD::SETCC);
655 setTargetDAGCombine(ISD::SELECT_CC);
658 // Use reciprocal estimates.
659 if (TM.Options.UnsafeFPMath) {
660 setTargetDAGCombine(ISD::FDIV);
661 setTargetDAGCombine(ISD::FSQRT);
664 // Darwin long double math library functions have $LDBL128 appended.
665 if (Subtarget->isDarwin()) {
666 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
667 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
668 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
669 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
670 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
671 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
672 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
673 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
674 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
675 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
678 // With 32 condition bits, we don't need to sink (and duplicate) compares
679 // aggressively in CodeGenPrep.
680 if (Subtarget->useCRBits())
681 setHasMultipleConditionRegisters();
683 setMinFunctionAlignment(2);
684 if (PPCSubTarget.isDarwin())
685 setPrefFunctionAlignment(4);
687 if (isPPC64 && Subtarget->isJITCodeModel())
688 // Temporary workaround for the inability of PPC64 JIT to handle jump
690 setSupportJumpTables(false);
692 setInsertFencesForAtomic(true);
694 if (Subtarget->enableMachineScheduler())
695 setSchedulingPreference(Sched::Source);
697 setSchedulingPreference(Sched::Hybrid);
699 computeRegisterProperties();
701 // The Freescale cores does better with aggressive inlining of memcpy and
702 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
703 if (Subtarget->getDarwinDirective() == PPC::DIR_E500mc ||
704 Subtarget->getDarwinDirective() == PPC::DIR_E5500) {
705 MaxStoresPerMemset = 32;
706 MaxStoresPerMemsetOptSize = 16;
707 MaxStoresPerMemcpy = 32;
708 MaxStoresPerMemcpyOptSize = 8;
709 MaxStoresPerMemmove = 32;
710 MaxStoresPerMemmoveOptSize = 8;
712 setPrefFunctionAlignment(4);
716 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
717 /// the desired ByVal argument alignment.
718 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
719 unsigned MaxMaxAlign) {
720 if (MaxAlign == MaxMaxAlign)
722 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
723 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
725 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
727 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
728 unsigned EltAlign = 0;
729 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
730 if (EltAlign > MaxAlign)
732 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
733 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
734 unsigned EltAlign = 0;
735 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
736 if (EltAlign > MaxAlign)
738 if (MaxAlign == MaxMaxAlign)
744 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
745 /// function arguments in the caller parameter area.
746 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
747 // Darwin passes everything on 4 byte boundary.
748 if (PPCSubTarget.isDarwin())
751 // 16byte and wider vectors are passed on 16byte boundary.
752 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
753 unsigned Align = PPCSubTarget.isPPC64() ? 8 : 4;
754 if (PPCSubTarget.hasAltivec() || PPCSubTarget.hasQPX())
755 getMaxByValAlign(Ty, Align, PPCSubTarget.hasQPX() ? 32 : 16);
759 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
761 default: return nullptr;
762 case PPCISD::FSEL: return "PPCISD::FSEL";
763 case PPCISD::FCFID: return "PPCISD::FCFID";
764 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
765 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
766 case PPCISD::FRE: return "PPCISD::FRE";
767 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
768 case PPCISD::STFIWX: return "PPCISD::STFIWX";
769 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
770 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
771 case PPCISD::VPERM: return "PPCISD::VPERM";
772 case PPCISD::Hi: return "PPCISD::Hi";
773 case PPCISD::Lo: return "PPCISD::Lo";
774 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
775 case PPCISD::TOC_RESTORE: return "PPCISD::TOC_RESTORE";
776 case PPCISD::LOAD: return "PPCISD::LOAD";
777 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
778 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
779 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
780 case PPCISD::SRL: return "PPCISD::SRL";
781 case PPCISD::SRA: return "PPCISD::SRA";
782 case PPCISD::SHL: return "PPCISD::SHL";
783 case PPCISD::CALL: return "PPCISD::CALL";
784 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
785 case PPCISD::MTCTR: return "PPCISD::MTCTR";
786 case PPCISD::BCTRL: return "PPCISD::BCTRL";
787 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
788 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
789 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
790 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
791 case PPCISD::VCMP: return "PPCISD::VCMP";
792 case PPCISD::VCMPo: return "PPCISD::VCMPo";
793 case PPCISD::LBRX: return "PPCISD::LBRX";
794 case PPCISD::STBRX: return "PPCISD::STBRX";
795 case PPCISD::LARX: return "PPCISD::LARX";
796 case PPCISD::STCX: return "PPCISD::STCX";
797 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
798 case PPCISD::BDNZ: return "PPCISD::BDNZ";
799 case PPCISD::BDZ: return "PPCISD::BDZ";
800 case PPCISD::MFFS: return "PPCISD::MFFS";
801 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
802 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
803 case PPCISD::CR6SET: return "PPCISD::CR6SET";
804 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
805 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
806 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
807 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
808 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
809 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
810 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
811 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
812 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
813 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
814 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
815 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
816 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
817 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
818 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
819 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
820 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
821 case PPCISD::SC: return "PPCISD::SC";
825 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
827 return PPCSubTarget.useCRBits() ? MVT::i1 : MVT::i32;
828 return VT.changeVectorElementTypeToInteger();
831 //===----------------------------------------------------------------------===//
832 // Node matching predicates, for use by the tblgen matching code.
833 //===----------------------------------------------------------------------===//
835 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
836 static bool isFloatingPointZero(SDValue Op) {
837 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
838 return CFP->getValueAPF().isZero();
839 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
840 // Maybe this has already been legalized into the constant pool?
841 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
842 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
843 return CFP->getValueAPF().isZero();
848 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
849 /// true if Op is undef or if it matches the specified value.
850 static bool isConstantOrUndef(int Op, int Val) {
851 return Op < 0 || Op == Val;
854 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
855 /// VPKUHUM instruction.
856 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
858 for (unsigned i = 0; i != 16; ++i)
859 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
862 for (unsigned i = 0; i != 8; ++i)
863 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) ||
864 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1))
870 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
871 /// VPKUWUM instruction.
872 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
874 for (unsigned i = 0; i != 16; i += 2)
875 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
876 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
879 for (unsigned i = 0; i != 8; i += 2)
880 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
881 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) ||
882 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) ||
883 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3))
889 /// isVMerge - Common function, used to match vmrg* shuffles.
891 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
892 unsigned LHSStart, unsigned RHSStart) {
893 if (N->getValueType(0) != MVT::v16i8)
895 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
896 "Unsupported merge size!");
898 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
899 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
900 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
901 LHSStart+j+i*UnitSize) ||
902 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
903 RHSStart+j+i*UnitSize))
909 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
910 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
911 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
914 return isVMerge(N, UnitSize, 8, 24);
915 return isVMerge(N, UnitSize, 8, 8);
918 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
919 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
920 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
923 return isVMerge(N, UnitSize, 0, 16);
924 return isVMerge(N, UnitSize, 0, 0);
928 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
929 /// amount, otherwise return -1.
930 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
931 if (N->getValueType(0) != MVT::v16i8)
934 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
936 // Find the first non-undef value in the shuffle mask.
938 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
941 if (i == 16) return -1; // all undef.
943 // Otherwise, check to see if the rest of the elements are consecutively
944 // numbered from this value.
945 unsigned ShiftAmt = SVOp->getMaskElt(i);
946 if (ShiftAmt < i) return -1;
950 // Check the rest of the elements to see if they are consecutive.
951 for (++i; i != 16; ++i)
952 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
955 // Check the rest of the elements to see if they are consecutive.
956 for (++i; i != 16; ++i)
957 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
963 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
964 /// specifies a splat of a single element that is suitable for input to
965 /// VSPLTB/VSPLTH/VSPLTW.
966 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
967 assert(N->getValueType(0) == MVT::v16i8 &&
968 (EltSize == 1 || EltSize == 2 || EltSize == 4));
970 // This is a splat operation if each element of the permute is the same, and
971 // if the value doesn't reference the second vector.
972 unsigned ElementBase = N->getMaskElt(0);
974 // FIXME: Handle UNDEF elements too!
975 if (ElementBase >= 16)
978 // Check that the indices are consecutive, in the case of a multi-byte element
979 // splatted with a v16i8 mask.
980 for (unsigned i = 1; i != EltSize; ++i)
981 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
984 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
985 if (N->getMaskElt(i) < 0) continue;
986 for (unsigned j = 0; j != EltSize; ++j)
987 if (N->getMaskElt(i+j) != N->getMaskElt(j))
993 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
995 bool PPC::isAllNegativeZeroVector(SDNode *N) {
996 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
998 APInt APVal, APUndef;
1002 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1003 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1004 return CFP->getValueAPF().isNegZero();
1009 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1010 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1011 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
1012 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1013 assert(isSplatShuffleMask(SVOp, EltSize));
1014 return SVOp->getMaskElt(0) / EltSize;
1017 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1018 /// by using a vspltis[bhw] instruction of the specified element size, return
1019 /// the constant being splatted. The ByteSize field indicates the number of
1020 /// bytes of each element [124] -> [bhw].
1021 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1022 SDValue OpVal(nullptr, 0);
1024 // If ByteSize of the splat is bigger than the element size of the
1025 // build_vector, then we have a case where we are checking for a splat where
1026 // multiple elements of the buildvector are folded together into a single
1027 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1028 unsigned EltSize = 16/N->getNumOperands();
1029 if (EltSize < ByteSize) {
1030 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1031 SDValue UniquedVals[4];
1032 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1034 // See if all of the elements in the buildvector agree across.
1035 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1036 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1037 // If the element isn't a constant, bail fully out.
1038 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1041 if (!UniquedVals[i&(Multiple-1)].getNode())
1042 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1043 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1044 return SDValue(); // no match.
1047 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1048 // either constant or undef values that are identical for each chunk. See
1049 // if these chunks can form into a larger vspltis*.
1051 // Check to see if all of the leading entries are either 0 or -1. If
1052 // neither, then this won't fit into the immediate field.
1053 bool LeadingZero = true;
1054 bool LeadingOnes = true;
1055 for (unsigned i = 0; i != Multiple-1; ++i) {
1056 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1058 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1059 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1061 // Finally, check the least significant entry.
1063 if (!UniquedVals[Multiple-1].getNode())
1064 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
1065 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1067 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
1070 if (!UniquedVals[Multiple-1].getNode())
1071 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
1072 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1073 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1074 return DAG.getTargetConstant(Val, MVT::i32);
1080 // Check to see if this buildvec has a single non-undef value in its elements.
1081 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1082 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1083 if (!OpVal.getNode())
1084 OpVal = N->getOperand(i);
1085 else if (OpVal != N->getOperand(i))
1089 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1091 unsigned ValSizeInBytes = EltSize;
1093 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1094 Value = CN->getZExtValue();
1095 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1096 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1097 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1100 // If the splat value is larger than the element value, then we can never do
1101 // this splat. The only case that we could fit the replicated bits into our
1102 // immediate field for would be zero, and we prefer to use vxor for it.
1103 if (ValSizeInBytes < ByteSize) return SDValue();
1105 // If the element value is larger than the splat value, cut it in half and
1106 // check to see if the two halves are equal. Continue doing this until we
1107 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
1108 while (ValSizeInBytes > ByteSize) {
1109 ValSizeInBytes >>= 1;
1111 // If the top half equals the bottom half, we're still ok.
1112 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1113 (Value & ((1 << (8*ValSizeInBytes))-1)))
1117 // Properly sign extend the value.
1118 int MaskVal = SignExtend32(Value, ByteSize * 8);
1120 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1121 if (MaskVal == 0) return SDValue();
1123 // Finally, if this value fits in a 5 bit sext field, return it
1124 if (SignExtend32<5>(MaskVal) == MaskVal)
1125 return DAG.getTargetConstant(MaskVal, MVT::i32);
1129 //===----------------------------------------------------------------------===//
1130 // Addressing Mode Selection
1131 //===----------------------------------------------------------------------===//
1133 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1134 /// or 64-bit immediate, and if the value can be accurately represented as a
1135 /// sign extension from a 16-bit value. If so, this returns true and the
1137 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1138 if (N->getOpcode() != ISD::Constant)
1141 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1142 if (N->getValueType(0) == MVT::i32)
1143 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1145 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1147 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1148 return isIntS16Immediate(Op.getNode(), Imm);
1152 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1153 /// can be represented as an indexed [r+r] operation. Returns false if it
1154 /// can be more efficiently represented with [r+imm].
1155 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1157 SelectionDAG &DAG) const {
1159 if (N.getOpcode() == ISD::ADD) {
1160 if (isIntS16Immediate(N.getOperand(1), imm))
1161 return false; // r+i
1162 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1163 return false; // r+i
1165 Base = N.getOperand(0);
1166 Index = N.getOperand(1);
1168 } else if (N.getOpcode() == ISD::OR) {
1169 if (isIntS16Immediate(N.getOperand(1), imm))
1170 return false; // r+i can fold it if we can.
1172 // If this is an or of disjoint bitfields, we can codegen this as an add
1173 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1175 APInt LHSKnownZero, LHSKnownOne;
1176 APInt RHSKnownZero, RHSKnownOne;
1177 DAG.ComputeMaskedBits(N.getOperand(0),
1178 LHSKnownZero, LHSKnownOne);
1180 if (LHSKnownZero.getBoolValue()) {
1181 DAG.ComputeMaskedBits(N.getOperand(1),
1182 RHSKnownZero, RHSKnownOne);
1183 // If all of the bits are known zero on the LHS or RHS, the add won't
1185 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1186 Base = N.getOperand(0);
1187 Index = N.getOperand(1);
1196 // If we happen to be doing an i64 load or store into a stack slot that has
1197 // less than a 4-byte alignment, then the frame-index elimination may need to
1198 // use an indexed load or store instruction (because the offset may not be a
1199 // multiple of 4). The extra register needed to hold the offset comes from the
1200 // register scavenger, and it is possible that the scavenger will need to use
1201 // an emergency spill slot. As a result, we need to make sure that a spill slot
1202 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1204 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1205 // FIXME: This does not handle the LWA case.
1209 // NOTE: We'll exclude negative FIs here, which come from argument
1210 // lowering, because there are no known test cases triggering this problem
1211 // using packed structures (or similar). We can remove this exclusion if
1212 // we find such a test case. The reason why this is so test-case driven is
1213 // because this entire 'fixup' is only to prevent crashes (from the
1214 // register scavenger) on not-really-valid inputs. For example, if we have:
1216 // %b = bitcast i1* %a to i64*
1217 // store i64* a, i64 b
1218 // then the store should really be marked as 'align 1', but is not. If it
1219 // were marked as 'align 1' then the indexed form would have been
1220 // instruction-selected initially, and the problem this 'fixup' is preventing
1221 // won't happen regardless.
1225 MachineFunction &MF = DAG.getMachineFunction();
1226 MachineFrameInfo *MFI = MF.getFrameInfo();
1228 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1232 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1233 FuncInfo->setHasNonRISpills();
1236 /// Returns true if the address N can be represented by a base register plus
1237 /// a signed 16-bit displacement [r+imm], and if it is not better
1238 /// represented as reg+reg. If Aligned is true, only accept displacements
1239 /// suitable for STD and friends, i.e. multiples of 4.
1240 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1243 bool Aligned) const {
1244 // FIXME dl should come from parent load or store, not from address
1246 // If this can be more profitably realized as r+r, fail.
1247 if (SelectAddressRegReg(N, Disp, Base, DAG))
1250 if (N.getOpcode() == ISD::ADD) {
1252 if (isIntS16Immediate(N.getOperand(1), imm) &&
1253 (!Aligned || (imm & 3) == 0)) {
1254 Disp = DAG.getTargetConstant(imm, N.getValueType());
1255 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1256 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1257 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1259 Base = N.getOperand(0);
1261 return true; // [r+i]
1262 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1263 // Match LOAD (ADD (X, Lo(G))).
1264 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1265 && "Cannot handle constant offsets yet!");
1266 Disp = N.getOperand(1).getOperand(0); // The global address.
1267 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1268 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1269 Disp.getOpcode() == ISD::TargetConstantPool ||
1270 Disp.getOpcode() == ISD::TargetJumpTable);
1271 Base = N.getOperand(0);
1272 return true; // [&g+r]
1274 } else if (N.getOpcode() == ISD::OR) {
1276 if (isIntS16Immediate(N.getOperand(1), imm) &&
1277 (!Aligned || (imm & 3) == 0)) {
1278 // If this is an or of disjoint bitfields, we can codegen this as an add
1279 // (for better address arithmetic) if the LHS and RHS of the OR are
1280 // provably disjoint.
1281 APInt LHSKnownZero, LHSKnownOne;
1282 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1284 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1285 // If all of the bits are known zero on the LHS or RHS, the add won't
1287 Base = N.getOperand(0);
1288 Disp = DAG.getTargetConstant(imm, N.getValueType());
1292 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1293 // Loading from a constant address.
1295 // If this address fits entirely in a 16-bit sext immediate field, codegen
1298 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1299 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1300 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1301 CN->getValueType(0));
1305 // Handle 32-bit sext immediates with LIS + addr mode.
1306 if ((CN->getValueType(0) == MVT::i32 ||
1307 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1308 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1309 int Addr = (int)CN->getZExtValue();
1311 // Otherwise, break this down into an LIS + disp.
1312 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1314 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1315 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1316 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1321 Disp = DAG.getTargetConstant(0, getPointerTy());
1322 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1323 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1324 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1327 return true; // [r+0]
1330 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1331 /// represented as an indexed [r+r] operation.
1332 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1334 SelectionDAG &DAG) const {
1335 // Check to see if we can easily represent this as an [r+r] address. This
1336 // will fail if it thinks that the address is more profitably represented as
1337 // reg+imm, e.g. where imm = 0.
1338 if (SelectAddressRegReg(N, Base, Index, DAG))
1341 // If the operand is an addition, always emit this as [r+r], since this is
1342 // better (for code size, and execution, as the memop does the add for free)
1343 // than emitting an explicit add.
1344 if (N.getOpcode() == ISD::ADD) {
1345 Base = N.getOperand(0);
1346 Index = N.getOperand(1);
1350 // Otherwise, do it the hard way, using R0 as the base register.
1351 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1357 /// getPreIndexedAddressParts - returns true by value, base pointer and
1358 /// offset pointer and addressing mode by reference if the node's address
1359 /// can be legally represented as pre-indexed load / store address.
1360 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1362 ISD::MemIndexedMode &AM,
1363 SelectionDAG &DAG) const {
1364 if (DisablePPCPreinc) return false;
1370 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1371 Ptr = LD->getBasePtr();
1372 VT = LD->getMemoryVT();
1373 Alignment = LD->getAlignment();
1374 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1375 Ptr = ST->getBasePtr();
1376 VT = ST->getMemoryVT();
1377 Alignment = ST->getAlignment();
1382 // PowerPC doesn't have preinc load/store instructions for vectors.
1386 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1388 // Common code will reject creating a pre-inc form if the base pointer
1389 // is a frame index, or if N is a store and the base pointer is either
1390 // the same as or a predecessor of the value being stored. Check for
1391 // those situations here, and try with swapped Base/Offset instead.
1394 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1397 SDValue Val = cast<StoreSDNode>(N)->getValue();
1398 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1403 std::swap(Base, Offset);
1409 // LDU/STU can only handle immediates that are a multiple of 4.
1410 if (VT != MVT::i64) {
1411 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1414 // LDU/STU need an address with at least 4-byte alignment.
1418 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1422 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1423 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1424 // sext i32 to i64 when addr mode is r+i.
1425 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1426 LD->getExtensionType() == ISD::SEXTLOAD &&
1427 isa<ConstantSDNode>(Offset))
1435 //===----------------------------------------------------------------------===//
1436 // LowerOperation implementation
1437 //===----------------------------------------------------------------------===//
1439 /// GetLabelAccessInfo - Return true if we should reference labels using a
1440 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1441 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1442 unsigned &LoOpFlags,
1443 const GlobalValue *GV = nullptr) {
1444 HiOpFlags = PPCII::MO_HA;
1445 LoOpFlags = PPCII::MO_LO;
1447 // Don't use the pic base if not in PIC relocation model. Or if we are on a
1448 // non-darwin platform. We don't support PIC on other platforms yet.
1449 bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1450 TM.getSubtarget<PPCSubtarget>().isDarwin();
1452 HiOpFlags |= PPCII::MO_PIC_FLAG;
1453 LoOpFlags |= PPCII::MO_PIC_FLAG;
1456 // If this is a reference to a global value that requires a non-lazy-ptr, make
1457 // sure that instruction lowering adds it.
1458 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1459 HiOpFlags |= PPCII::MO_NLP_FLAG;
1460 LoOpFlags |= PPCII::MO_NLP_FLAG;
1462 if (GV->hasHiddenVisibility()) {
1463 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1464 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1471 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1472 SelectionDAG &DAG) {
1473 EVT PtrVT = HiPart.getValueType();
1474 SDValue Zero = DAG.getConstant(0, PtrVT);
1477 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1478 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1480 // With PIC, the first instruction is actually "GR+hi(&G)".
1482 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1483 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1485 // Generate non-pic code that has direct accesses to the constant pool.
1486 // The address of the global is just (hi(&g)+lo(&g)).
1487 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1490 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1491 SelectionDAG &DAG) const {
1492 EVT PtrVT = Op.getValueType();
1493 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1494 const Constant *C = CP->getConstVal();
1496 // 64-bit SVR4 ABI code is always position-independent.
1497 // The actual address of the GlobalValue is stored in the TOC.
1498 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1499 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1500 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1501 DAG.getRegister(PPC::X2, MVT::i64));
1504 unsigned MOHiFlag, MOLoFlag;
1505 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1507 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1509 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1510 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1513 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1514 EVT PtrVT = Op.getValueType();
1515 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1517 // 64-bit SVR4 ABI code is always position-independent.
1518 // The actual address of the GlobalValue is stored in the TOC.
1519 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1520 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1521 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1522 DAG.getRegister(PPC::X2, MVT::i64));
1525 unsigned MOHiFlag, MOLoFlag;
1526 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1527 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1528 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1529 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1532 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1533 SelectionDAG &DAG) const {
1534 EVT PtrVT = Op.getValueType();
1536 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1538 unsigned MOHiFlag, MOLoFlag;
1539 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1540 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1541 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1542 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1545 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1546 SelectionDAG &DAG) const {
1548 // FIXME: TLS addresses currently use medium model code sequences,
1549 // which is the most useful form. Eventually support for small and
1550 // large models could be added if users need it, at the cost of
1551 // additional complexity.
1552 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1554 const GlobalValue *GV = GA->getGlobal();
1555 EVT PtrVT = getPointerTy();
1556 bool is64bit = PPCSubTarget.isPPC64();
1558 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1560 if (Model == TLSModel::LocalExec) {
1561 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1562 PPCII::MO_TPREL_HA);
1563 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1564 PPCII::MO_TPREL_LO);
1565 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1566 is64bit ? MVT::i64 : MVT::i32);
1567 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1568 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1571 if (Model == TLSModel::InitialExec) {
1572 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1573 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1577 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1578 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1579 PtrVT, GOTReg, TGA);
1581 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1582 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1583 PtrVT, TGA, GOTPtr);
1584 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1587 if (Model == TLSModel::GeneralDynamic) {
1588 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1589 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1590 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1592 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1595 // We need a chain node, and don't have one handy. The underlying
1596 // call has no side effects, so using the function entry node
1598 SDValue Chain = DAG.getEntryNode();
1599 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1600 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1601 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1602 PtrVT, ParmReg, TGA);
1603 // The return value from GET_TLS_ADDR really is in X3 already, but
1604 // some hacks are needed here to tie everything together. The extra
1605 // copies dissolve during subsequent transforms.
1606 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1607 return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1610 if (Model == TLSModel::LocalDynamic) {
1611 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1612 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1613 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1615 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1618 // We need a chain node, and don't have one handy. The underlying
1619 // call has no side effects, so using the function entry node
1621 SDValue Chain = DAG.getEntryNode();
1622 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1623 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1624 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1625 PtrVT, ParmReg, TGA);
1626 // The return value from GET_TLSLD_ADDR really is in X3 already, but
1627 // some hacks are needed here to tie everything together. The extra
1628 // copies dissolve during subsequent transforms.
1629 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1630 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1631 Chain, ParmReg, TGA);
1632 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1635 llvm_unreachable("Unknown TLS model!");
1638 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1639 SelectionDAG &DAG) const {
1640 EVT PtrVT = Op.getValueType();
1641 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1643 const GlobalValue *GV = GSDN->getGlobal();
1645 // 64-bit SVR4 ABI code is always position-independent.
1646 // The actual address of the GlobalValue is stored in the TOC.
1647 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1648 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1649 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1650 DAG.getRegister(PPC::X2, MVT::i64));
1653 unsigned MOHiFlag, MOLoFlag;
1654 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1657 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1659 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1661 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1663 // If the global reference is actually to a non-lazy-pointer, we have to do an
1664 // extra load to get the address of the global.
1665 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1666 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1667 false, false, false, 0);
1671 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1672 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1675 if (Op.getValueType() == MVT::v2i64) {
1676 // When the operands themselves are v2i64 values, we need to do something
1677 // special because VSX has no underlying comparison operations for these.
1678 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1679 // Equality can be handled by casting to the legal type for Altivec
1680 // comparisons, everything else needs to be expanded.
1681 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1682 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1683 DAG.getSetCC(dl, MVT::v4i32,
1684 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1685 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1692 // We handle most of these in the usual way.
1696 // If we're comparing for equality to zero, expose the fact that this is
1697 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1698 // fold the new nodes.
1699 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1700 if (C->isNullValue() && CC == ISD::SETEQ) {
1701 EVT VT = Op.getOperand(0).getValueType();
1702 SDValue Zext = Op.getOperand(0);
1703 if (VT.bitsLT(MVT::i32)) {
1705 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1707 unsigned Log2b = Log2_32(VT.getSizeInBits());
1708 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1709 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1710 DAG.getConstant(Log2b, MVT::i32));
1711 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1713 // Leave comparisons against 0 and -1 alone for now, since they're usually
1714 // optimized. FIXME: revisit this when we can custom lower all setcc
1716 if (C->isAllOnesValue() || C->isNullValue())
1720 // If we have an integer seteq/setne, turn it into a compare against zero
1721 // by xor'ing the rhs with the lhs, which is faster than setting a
1722 // condition register, reading it back out, and masking the correct bit. The
1723 // normal approach here uses sub to do this instead of xor. Using xor exposes
1724 // the result to other bit-twiddling opportunities.
1725 EVT LHSVT = Op.getOperand(0).getValueType();
1726 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1727 EVT VT = Op.getValueType();
1728 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1730 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1735 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1736 const PPCSubtarget &Subtarget) const {
1737 SDNode *Node = Op.getNode();
1738 EVT VT = Node->getValueType(0);
1739 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1740 SDValue InChain = Node->getOperand(0);
1741 SDValue VAListPtr = Node->getOperand(1);
1742 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1745 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1748 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1749 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1751 InChain = GprIndex.getValue(1);
1753 if (VT == MVT::i64) {
1754 // Check if GprIndex is even
1755 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1756 DAG.getConstant(1, MVT::i32));
1757 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1758 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1759 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1760 DAG.getConstant(1, MVT::i32));
1761 // Align GprIndex to be even if it isn't
1762 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1766 // fpr index is 1 byte after gpr
1767 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1768 DAG.getConstant(1, MVT::i32));
1771 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1772 FprPtr, MachinePointerInfo(SV), MVT::i8,
1774 InChain = FprIndex.getValue(1);
1776 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1777 DAG.getConstant(8, MVT::i32));
1779 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1780 DAG.getConstant(4, MVT::i32));
1783 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1784 MachinePointerInfo(), false, false,
1786 InChain = OverflowArea.getValue(1);
1788 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1789 MachinePointerInfo(), false, false,
1791 InChain = RegSaveArea.getValue(1);
1793 // select overflow_area if index > 8
1794 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1795 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1797 // adjustment constant gpr_index * 4/8
1798 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1799 VT.isInteger() ? GprIndex : FprIndex,
1800 DAG.getConstant(VT.isInteger() ? 4 : 8,
1803 // OurReg = RegSaveArea + RegConstant
1804 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1807 // Floating types are 32 bytes into RegSaveArea
1808 if (VT.isFloatingPoint())
1809 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1810 DAG.getConstant(32, MVT::i32));
1812 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1813 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1814 VT.isInteger() ? GprIndex : FprIndex,
1815 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1818 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1819 VT.isInteger() ? VAListPtr : FprPtr,
1820 MachinePointerInfo(SV),
1821 MVT::i8, false, false, 0);
1823 // determine if we should load from reg_save_area or overflow_area
1824 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1826 // increase overflow_area by 4/8 if gpr/fpr > 8
1827 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1828 DAG.getConstant(VT.isInteger() ? 4 : 8,
1831 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1834 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1836 MachinePointerInfo(),
1837 MVT::i32, false, false, 0);
1839 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1840 false, false, false, 0);
1843 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
1844 const PPCSubtarget &Subtarget) const {
1845 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
1847 // We have to copy the entire va_list struct:
1848 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
1849 return DAG.getMemcpy(Op.getOperand(0), Op,
1850 Op.getOperand(1), Op.getOperand(2),
1851 DAG.getConstant(12, MVT::i32), 8, false, true,
1852 MachinePointerInfo(), MachinePointerInfo());
1855 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1856 SelectionDAG &DAG) const {
1857 return Op.getOperand(0);
1860 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1861 SelectionDAG &DAG) const {
1862 SDValue Chain = Op.getOperand(0);
1863 SDValue Trmp = Op.getOperand(1); // trampoline
1864 SDValue FPtr = Op.getOperand(2); // nested function
1865 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1868 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1869 bool isPPC64 = (PtrVT == MVT::i64);
1871 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1874 TargetLowering::ArgListTy Args;
1875 TargetLowering::ArgListEntry Entry;
1877 Entry.Ty = IntPtrTy;
1878 Entry.Node = Trmp; Args.push_back(Entry);
1880 // TrampSize == (isPPC64 ? 48 : 40);
1881 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1882 isPPC64 ? MVT::i64 : MVT::i32);
1883 Args.push_back(Entry);
1885 Entry.Node = FPtr; Args.push_back(Entry);
1886 Entry.Node = Nest; Args.push_back(Entry);
1888 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1889 TargetLowering::CallLoweringInfo CLI(Chain,
1890 Type::getVoidTy(*DAG.getContext()),
1891 false, false, false, false, 0,
1893 /*isTailCall=*/false,
1894 /*doesNotRet=*/false,
1895 /*isReturnValueUsed=*/true,
1896 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1898 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1900 return CallResult.second;
1903 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1904 const PPCSubtarget &Subtarget) const {
1905 MachineFunction &MF = DAG.getMachineFunction();
1906 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1910 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1911 // vastart just stores the address of the VarArgsFrameIndex slot into the
1912 // memory location argument.
1913 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1914 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1915 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1916 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1917 MachinePointerInfo(SV),
1921 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1922 // We suppose the given va_list is already allocated.
1925 // char gpr; /* index into the array of 8 GPRs
1926 // * stored in the register save area
1927 // * gpr=0 corresponds to r3,
1928 // * gpr=1 to r4, etc.
1930 // char fpr; /* index into the array of 8 FPRs
1931 // * stored in the register save area
1932 // * fpr=0 corresponds to f1,
1933 // * fpr=1 to f2, etc.
1935 // char *overflow_arg_area;
1936 // /* location on stack that holds
1937 // * the next overflow argument
1939 // char *reg_save_area;
1940 // /* where r3:r10 and f1:f8 (if saved)
1946 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1947 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1950 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1952 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1954 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1957 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1958 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1960 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1961 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1963 uint64_t FPROffset = 1;
1964 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1966 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1968 // Store first byte : number of int regs
1969 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1971 MachinePointerInfo(SV),
1972 MVT::i8, false, false, 0);
1973 uint64_t nextOffset = FPROffset;
1974 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1977 // Store second byte : number of float regs
1978 SDValue secondStore =
1979 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1980 MachinePointerInfo(SV, nextOffset), MVT::i8,
1982 nextOffset += StackOffset;
1983 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1985 // Store second word : arguments given on stack
1986 SDValue thirdStore =
1987 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1988 MachinePointerInfo(SV, nextOffset),
1990 nextOffset += FrameOffset;
1991 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1993 // Store third word : arguments given in registers
1994 return DAG.getStore(thirdStore, dl, FR, nextPtr,
1995 MachinePointerInfo(SV, nextOffset),
2000 #include "PPCGenCallingConv.inc"
2002 // Function whose sole purpose is to kill compiler warnings
2003 // stemming from unused functions included from PPCGenCallingConv.inc.
2004 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2005 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2008 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2009 CCValAssign::LocInfo &LocInfo,
2010 ISD::ArgFlagsTy &ArgFlags,
2015 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2017 CCValAssign::LocInfo &LocInfo,
2018 ISD::ArgFlagsTy &ArgFlags,
2020 static const MCPhysReg ArgRegs[] = {
2021 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2022 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2024 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2026 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2028 // Skip one register if the first unallocated register has an even register
2029 // number and there are still argument registers available which have not been
2030 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2031 // need to skip a register if RegNum is odd.
2032 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2033 State.AllocateReg(ArgRegs[RegNum]);
2036 // Always return false here, as this function only makes sure that the first
2037 // unallocated register has an odd register number and does not actually
2038 // allocate a register for the current argument.
2042 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2044 CCValAssign::LocInfo &LocInfo,
2045 ISD::ArgFlagsTy &ArgFlags,
2047 static const MCPhysReg ArgRegs[] = {
2048 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2052 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2054 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2056 // If there is only one Floating-point register left we need to put both f64
2057 // values of a split ppc_fp128 value on the stack.
2058 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2059 State.AllocateReg(ArgRegs[RegNum]);
2062 // Always return false here, as this function only makes sure that the two f64
2063 // values a ppc_fp128 value is split into are both passed in registers or both
2064 // passed on the stack and does not actually allocate a register for the
2065 // current argument.
2069 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2071 static const MCPhysReg *GetFPR() {
2072 static const MCPhysReg FPR[] = {
2073 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2074 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2080 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2082 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2083 unsigned PtrByteSize) {
2084 unsigned ArgSize = ArgVT.getStoreSize();
2085 if (Flags.isByVal())
2086 ArgSize = Flags.getByValSize();
2087 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2093 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2094 CallingConv::ID CallConv, bool isVarArg,
2095 const SmallVectorImpl<ISD::InputArg>
2097 SDLoc dl, SelectionDAG &DAG,
2098 SmallVectorImpl<SDValue> &InVals)
2100 if (PPCSubTarget.isSVR4ABI()) {
2101 if (PPCSubTarget.isPPC64())
2102 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2105 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2108 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2114 PPCTargetLowering::LowerFormalArguments_32SVR4(
2116 CallingConv::ID CallConv, bool isVarArg,
2117 const SmallVectorImpl<ISD::InputArg>
2119 SDLoc dl, SelectionDAG &DAG,
2120 SmallVectorImpl<SDValue> &InVals) const {
2122 // 32-bit SVR4 ABI Stack Frame Layout:
2123 // +-----------------------------------+
2124 // +--> | Back chain |
2125 // | +-----------------------------------+
2126 // | | Floating-point register save area |
2127 // | +-----------------------------------+
2128 // | | General register save area |
2129 // | +-----------------------------------+
2130 // | | CR save word |
2131 // | +-----------------------------------+
2132 // | | VRSAVE save word |
2133 // | +-----------------------------------+
2134 // | | Alignment padding |
2135 // | +-----------------------------------+
2136 // | | Vector register save area |
2137 // | +-----------------------------------+
2138 // | | Local variable space |
2139 // | +-----------------------------------+
2140 // | | Parameter list area |
2141 // | +-----------------------------------+
2142 // | | LR save word |
2143 // | +-----------------------------------+
2144 // SP--> +--- | Back chain |
2145 // +-----------------------------------+
2148 // System V Application Binary Interface PowerPC Processor Supplement
2149 // AltiVec Technology Programming Interface Manual
2151 MachineFunction &MF = DAG.getMachineFunction();
2152 MachineFrameInfo *MFI = MF.getFrameInfo();
2153 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2155 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2156 // Potential tail calls could cause overwriting of argument stack slots.
2157 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2158 (CallConv == CallingConv::Fast));
2159 unsigned PtrByteSize = 4;
2161 // Assign locations to all of the incoming arguments.
2162 SmallVector<CCValAssign, 16> ArgLocs;
2163 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2164 getTargetMachine(), ArgLocs, *DAG.getContext());
2166 // Reserve space for the linkage area on the stack.
2167 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
2169 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2171 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2172 CCValAssign &VA = ArgLocs[i];
2174 // Arguments stored in registers.
2175 if (VA.isRegLoc()) {
2176 const TargetRegisterClass *RC;
2177 EVT ValVT = VA.getValVT();
2179 switch (ValVT.getSimpleVT().SimpleTy) {
2181 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2184 RC = &PPC::GPRCRegClass;
2187 RC = &PPC::F4RCRegClass;
2190 if (PPCSubTarget.hasVSX())
2191 RC = &PPC::VSFRCRegClass;
2193 RC = &PPC::F8RCRegClass;
2199 RC = &PPC::VRRCRegClass;
2203 RC = &PPC::VSHRCRegClass;
2207 // Transform the arguments stored in physical registers into virtual ones.
2208 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2209 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2210 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2212 if (ValVT == MVT::i1)
2213 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2215 InVals.push_back(ArgValue);
2217 // Argument stored in memory.
2218 assert(VA.isMemLoc());
2220 unsigned ArgSize = VA.getLocVT().getStoreSize();
2221 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2224 // Create load nodes to retrieve arguments from the stack.
2225 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2226 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2227 MachinePointerInfo(),
2228 false, false, false, 0));
2232 // Assign locations to all of the incoming aggregate by value arguments.
2233 // Aggregates passed by value are stored in the local variable space of the
2234 // caller's stack frame, right above the parameter list area.
2235 SmallVector<CCValAssign, 16> ByValArgLocs;
2236 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2237 getTargetMachine(), ByValArgLocs, *DAG.getContext());
2239 // Reserve stack space for the allocations in CCInfo.
2240 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2242 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2244 // Area that is at least reserved in the caller of this function.
2245 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2247 // Set the size that is at least reserved in caller of this function. Tail
2248 // call optimized function's reserved stack space needs to be aligned so that
2249 // taking the difference between two stack areas will result in an aligned
2251 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2254 std::max(MinReservedArea,
2255 PPCFrameLowering::getMinCallFrameSize(false, false));
2257 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
2258 getStackAlignment();
2259 unsigned AlignMask = TargetAlign-1;
2260 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2262 FI->setMinReservedArea(MinReservedArea);
2264 SmallVector<SDValue, 8> MemOps;
2266 // If the function takes variable number of arguments, make a frame index for
2267 // the start of the first vararg value... for expansion of llvm.va_start.
2269 static const MCPhysReg GPArgRegs[] = {
2270 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2271 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2273 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2275 static const MCPhysReg FPArgRegs[] = {
2276 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2279 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2281 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2283 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2286 // Make room for NumGPArgRegs and NumFPArgRegs.
2287 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2288 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2290 FuncInfo->setVarArgsStackOffset(
2291 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2292 CCInfo.getNextStackOffset(), true));
2294 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2295 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2297 // The fixed integer arguments of a variadic function are stored to the
2298 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2299 // the result of va_next.
2300 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2301 // Get an existing live-in vreg, or add a new one.
2302 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2304 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2306 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2307 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2308 MachinePointerInfo(), false, false, 0);
2309 MemOps.push_back(Store);
2310 // Increment the address by four for the next argument to store
2311 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2312 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2315 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2317 // The double arguments are stored to the VarArgsFrameIndex
2319 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2320 // Get an existing live-in vreg, or add a new one.
2321 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2323 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2325 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2326 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2327 MachinePointerInfo(), false, false, 0);
2328 MemOps.push_back(Store);
2329 // Increment the address by eight for the next argument to store
2330 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2332 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2336 if (!MemOps.empty())
2337 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2342 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2343 // value to MVT::i64 and then truncate to the correct register size.
2345 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2346 SelectionDAG &DAG, SDValue ArgVal,
2349 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2350 DAG.getValueType(ObjectVT));
2351 else if (Flags.isZExt())
2352 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2353 DAG.getValueType(ObjectVT));
2355 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2358 // Set the size that is at least reserved in caller of this function. Tail
2359 // call optimized functions' reserved stack space needs to be aligned so that
2360 // taking the difference between two stack areas will result in an aligned
2363 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG,
2364 unsigned nAltivecParamsAtEnd,
2365 unsigned MinReservedArea,
2366 bool isPPC64) const {
2367 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2368 // Add the Altivec parameters at the end, if needed.
2369 if (nAltivecParamsAtEnd) {
2370 MinReservedArea = ((MinReservedArea+15)/16)*16;
2371 MinReservedArea += 16*nAltivecParamsAtEnd;
2374 std::max(MinReservedArea,
2375 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2376 unsigned TargetAlign
2377 = DAG.getMachineFunction().getTarget().getFrameLowering()->
2378 getStackAlignment();
2379 unsigned AlignMask = TargetAlign-1;
2380 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2381 FI->setMinReservedArea(MinReservedArea);
2385 PPCTargetLowering::LowerFormalArguments_64SVR4(
2387 CallingConv::ID CallConv, bool isVarArg,
2388 const SmallVectorImpl<ISD::InputArg>
2390 SDLoc dl, SelectionDAG &DAG,
2391 SmallVectorImpl<SDValue> &InVals) const {
2392 // TODO: add description of PPC stack frame format, or at least some docs.
2394 MachineFunction &MF = DAG.getMachineFunction();
2395 MachineFrameInfo *MFI = MF.getFrameInfo();
2396 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2398 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2399 // Potential tail calls could cause overwriting of argument stack slots.
2400 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2401 (CallConv == CallingConv::Fast));
2402 unsigned PtrByteSize = 8;
2404 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
2405 // Area that is at least reserved in caller of this function.
2406 unsigned MinReservedArea = ArgOffset;
2408 static const MCPhysReg GPR[] = {
2409 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2410 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2413 static const MCPhysReg *FPR = GetFPR();
2415 static const MCPhysReg VR[] = {
2416 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2417 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2419 static const MCPhysReg VSRH[] = {
2420 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2421 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2424 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2425 const unsigned Num_FPR_Regs = 13;
2426 const unsigned Num_VR_Regs = array_lengthof(VR);
2428 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2430 // Add DAG nodes to load the arguments or copy them out of registers. On
2431 // entry to a function on PPC, the arguments start after the linkage area,
2432 // although the first ones are often in registers.
2434 SmallVector<SDValue, 8> MemOps;
2435 unsigned nAltivecParamsAtEnd = 0;
2436 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2437 unsigned CurArgIdx = 0;
2438 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2440 bool needsLoad = false;
2441 EVT ObjectVT = Ins[ArgNo].VT;
2442 unsigned ObjSize = ObjectVT.getStoreSize();
2443 unsigned ArgSize = ObjSize;
2444 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2445 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2446 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2448 unsigned CurArgOffset = ArgOffset;
2450 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2451 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2452 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8 ||
2453 ObjectVT==MVT::v2f64 || ObjectVT==MVT::v2i64) {
2455 MinReservedArea = ((MinReservedArea+15)/16)*16;
2456 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2460 nAltivecParamsAtEnd++;
2462 // Calculate min reserved area.
2463 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2467 // FIXME the codegen can be much improved in some cases.
2468 // We do not have to keep everything in memory.
2469 if (Flags.isByVal()) {
2470 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2471 ObjSize = Flags.getByValSize();
2472 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2473 // Empty aggregate parameters do not take up registers. Examples:
2477 // etc. However, we have to provide a place-holder in InVals, so
2478 // pretend we have an 8-byte item at the current address for that
2481 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2482 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2483 InVals.push_back(FIN);
2487 unsigned BVAlign = Flags.getByValAlign();
2489 ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
2490 CurArgOffset = ArgOffset;
2493 // All aggregates smaller than 8 bytes must be passed right-justified.
2494 if (ObjSize < PtrByteSize)
2495 CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize);
2496 // The value of the object is its address.
2497 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2498 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2499 InVals.push_back(FIN);
2502 if (GPR_idx != Num_GPR_Regs) {
2503 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2504 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2507 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2508 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2509 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2510 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2511 MachinePointerInfo(FuncArg),
2512 ObjType, false, false, 0);
2514 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2515 // store the whole register as-is to the parameter save area
2516 // slot. The address of the parameter was already calculated
2517 // above (InVals.push_back(FIN)) to be the right-justified
2518 // offset within the slot. For this store, we need a new
2519 // frame index that points at the beginning of the slot.
2520 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2521 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2522 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2523 MachinePointerInfo(FuncArg),
2527 MemOps.push_back(Store);
2530 // Whether we copied from a register or not, advance the offset
2531 // into the parameter save area by a full doubleword.
2532 ArgOffset += PtrByteSize;
2536 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2537 // Store whatever pieces of the object are in registers
2538 // to memory. ArgOffset will be the address of the beginning
2540 if (GPR_idx != Num_GPR_Regs) {
2542 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2543 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2544 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2545 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2546 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2547 MachinePointerInfo(FuncArg, j),
2549 MemOps.push_back(Store);
2551 ArgOffset += PtrByteSize;
2553 ArgOffset += ArgSize - j;
2560 switch (ObjectVT.getSimpleVT().SimpleTy) {
2561 default: llvm_unreachable("Unhandled argument type!");
2565 if (GPR_idx != Num_GPR_Regs) {
2566 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2567 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2569 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2570 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2571 // value to MVT::i64 and then truncate to the correct register size.
2572 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2577 ArgSize = PtrByteSize;
2584 // Every 8 bytes of argument space consumes one of the GPRs available for
2585 // argument passing.
2586 if (GPR_idx != Num_GPR_Regs) {
2589 if (FPR_idx != Num_FPR_Regs) {
2592 if (ObjectVT == MVT::f32)
2593 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2595 VReg = MF.addLiveIn(FPR[FPR_idx], PPCSubTarget.hasVSX() ?
2596 &PPC::VSFRCRegClass :
2597 &PPC::F8RCRegClass);
2599 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2603 ArgSize = PtrByteSize;
2614 // Note that vector arguments in registers don't reserve stack space,
2615 // except in varargs functions.
2616 if (VR_idx != Num_VR_Regs) {
2617 unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2618 MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2619 MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2620 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2622 while ((ArgOffset % 16) != 0) {
2623 ArgOffset += PtrByteSize;
2624 if (GPR_idx != Num_GPR_Regs)
2628 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2632 // Vectors are aligned.
2633 ArgOffset = ((ArgOffset+15)/16)*16;
2634 CurArgOffset = ArgOffset;
2641 // We need to load the argument to a virtual register if we determined
2642 // above that we ran out of physical registers of the appropriate type.
2644 int FI = MFI->CreateFixedObject(ObjSize,
2645 CurArgOffset + (ArgSize - ObjSize),
2647 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2648 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2649 false, false, false, 0);
2652 InVals.push_back(ArgVal);
2655 // Set the size that is at least reserved in caller of this function. Tail
2656 // call optimized functions' reserved stack space needs to be aligned so that
2657 // taking the difference between two stack areas will result in an aligned
2659 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true);
2661 // If the function takes variable number of arguments, make a frame index for
2662 // the start of the first vararg value... for expansion of llvm.va_start.
2664 int Depth = ArgOffset;
2666 FuncInfo->setVarArgsFrameIndex(
2667 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2668 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2670 // If this function is vararg, store any remaining integer argument regs
2671 // to their spots on the stack so that they may be loaded by deferencing the
2672 // result of va_next.
2673 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2674 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2675 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2676 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2677 MachinePointerInfo(), false, false, 0);
2678 MemOps.push_back(Store);
2679 // Increment the address by four for the next argument to store
2680 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2681 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2685 if (!MemOps.empty())
2686 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2692 PPCTargetLowering::LowerFormalArguments_Darwin(
2694 CallingConv::ID CallConv, bool isVarArg,
2695 const SmallVectorImpl<ISD::InputArg>
2697 SDLoc dl, SelectionDAG &DAG,
2698 SmallVectorImpl<SDValue> &InVals) const {
2699 // TODO: add description of PPC stack frame format, or at least some docs.
2701 MachineFunction &MF = DAG.getMachineFunction();
2702 MachineFrameInfo *MFI = MF.getFrameInfo();
2703 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2705 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2706 bool isPPC64 = PtrVT == MVT::i64;
2707 // Potential tail calls could cause overwriting of argument stack slots.
2708 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2709 (CallConv == CallingConv::Fast));
2710 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2712 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
2713 // Area that is at least reserved in caller of this function.
2714 unsigned MinReservedArea = ArgOffset;
2716 static const MCPhysReg GPR_32[] = { // 32-bit registers.
2717 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2718 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2720 static const MCPhysReg GPR_64[] = { // 64-bit registers.
2721 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2722 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2725 static const MCPhysReg *FPR = GetFPR();
2727 static const MCPhysReg VR[] = {
2728 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2729 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2732 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2733 const unsigned Num_FPR_Regs = 13;
2734 const unsigned Num_VR_Regs = array_lengthof( VR);
2736 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2738 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
2740 // In 32-bit non-varargs functions, the stack space for vectors is after the
2741 // stack space for non-vectors. We do not use this space unless we have
2742 // too many vectors to fit in registers, something that only occurs in
2743 // constructed examples:), but we have to walk the arglist to figure
2744 // that out...for the pathological case, compute VecArgOffset as the
2745 // start of the vector parameter area. Computing VecArgOffset is the
2746 // entire point of the following loop.
2747 unsigned VecArgOffset = ArgOffset;
2748 if (!isVarArg && !isPPC64) {
2749 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2751 EVT ObjectVT = Ins[ArgNo].VT;
2752 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2754 if (Flags.isByVal()) {
2755 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2756 unsigned ObjSize = Flags.getByValSize();
2758 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2759 VecArgOffset += ArgSize;
2763 switch(ObjectVT.getSimpleVT().SimpleTy) {
2764 default: llvm_unreachable("Unhandled argument type!");
2770 case MVT::i64: // PPC64
2772 // FIXME: We are guaranteed to be !isPPC64 at this point.
2773 // Does MVT::i64 apply?
2780 // Nothing to do, we're only looking at Nonvector args here.
2785 // We've found where the vector parameter area in memory is. Skip the
2786 // first 12 parameters; these don't use that memory.
2787 VecArgOffset = ((VecArgOffset+15)/16)*16;
2788 VecArgOffset += 12*16;
2790 // Add DAG nodes to load the arguments or copy them out of registers. On
2791 // entry to a function on PPC, the arguments start after the linkage area,
2792 // although the first ones are often in registers.
2794 SmallVector<SDValue, 8> MemOps;
2795 unsigned nAltivecParamsAtEnd = 0;
2796 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2797 unsigned CurArgIdx = 0;
2798 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2800 bool needsLoad = false;
2801 EVT ObjectVT = Ins[ArgNo].VT;
2802 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2803 unsigned ArgSize = ObjSize;
2804 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2805 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2806 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2808 unsigned CurArgOffset = ArgOffset;
2810 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2811 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2812 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2813 if (isVarArg || isPPC64) {
2814 MinReservedArea = ((MinReservedArea+15)/16)*16;
2815 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2818 } else nAltivecParamsAtEnd++;
2820 // Calculate min reserved area.
2821 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2825 // FIXME the codegen can be much improved in some cases.
2826 // We do not have to keep everything in memory.
2827 if (Flags.isByVal()) {
2828 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2829 ObjSize = Flags.getByValSize();
2830 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2831 // Objects of size 1 and 2 are right justified, everything else is
2832 // left justified. This means the memory address is adjusted forwards.
2833 if (ObjSize==1 || ObjSize==2) {
2834 CurArgOffset = CurArgOffset + (4 - ObjSize);
2836 // The value of the object is its address.
2837 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2838 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2839 InVals.push_back(FIN);
2840 if (ObjSize==1 || ObjSize==2) {
2841 if (GPR_idx != Num_GPR_Regs) {
2844 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2846 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2847 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2848 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2849 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2850 MachinePointerInfo(FuncArg),
2851 ObjType, false, false, 0);
2852 MemOps.push_back(Store);
2856 ArgOffset += PtrByteSize;
2860 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2861 // Store whatever pieces of the object are in registers
2862 // to memory. ArgOffset will be the address of the beginning
2864 if (GPR_idx != Num_GPR_Regs) {
2867 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2869 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2870 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2871 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2872 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2873 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2874 MachinePointerInfo(FuncArg, j),
2876 MemOps.push_back(Store);
2878 ArgOffset += PtrByteSize;
2880 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2887 switch (ObjectVT.getSimpleVT().SimpleTy) {
2888 default: llvm_unreachable("Unhandled argument type!");
2892 if (GPR_idx != Num_GPR_Regs) {
2893 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2894 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2896 if (ObjectVT == MVT::i1)
2897 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
2902 ArgSize = PtrByteSize;
2904 // All int arguments reserve stack space in the Darwin ABI.
2905 ArgOffset += PtrByteSize;
2909 case MVT::i64: // PPC64
2910 if (GPR_idx != Num_GPR_Regs) {
2911 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2912 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2914 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2915 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2916 // value to MVT::i64 and then truncate to the correct register size.
2917 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2922 ArgSize = PtrByteSize;
2924 // All int arguments reserve stack space in the Darwin ABI.
2930 // Every 4 bytes of argument space consumes one of the GPRs available for
2931 // argument passing.
2932 if (GPR_idx != Num_GPR_Regs) {
2934 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2937 if (FPR_idx != Num_FPR_Regs) {
2940 if (ObjectVT == MVT::f32)
2941 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2943 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2945 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2951 // All FP arguments reserve stack space in the Darwin ABI.
2952 ArgOffset += isPPC64 ? 8 : ObjSize;
2958 // Note that vector arguments in registers don't reserve stack space,
2959 // except in varargs functions.
2960 if (VR_idx != Num_VR_Regs) {
2961 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2962 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2964 while ((ArgOffset % 16) != 0) {
2965 ArgOffset += PtrByteSize;
2966 if (GPR_idx != Num_GPR_Regs)
2970 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2974 if (!isVarArg && !isPPC64) {
2975 // Vectors go after all the nonvectors.
2976 CurArgOffset = VecArgOffset;
2979 // Vectors are aligned.
2980 ArgOffset = ((ArgOffset+15)/16)*16;
2981 CurArgOffset = ArgOffset;
2989 // We need to load the argument to a virtual register if we determined above
2990 // that we ran out of physical registers of the appropriate type.
2992 int FI = MFI->CreateFixedObject(ObjSize,
2993 CurArgOffset + (ArgSize - ObjSize),
2995 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2996 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2997 false, false, false, 0);
3000 InVals.push_back(ArgVal);
3003 // Set the size that is at least reserved in caller of this function. Tail
3004 // call optimized functions' reserved stack space needs to be aligned so that
3005 // taking the difference between two stack areas will result in an aligned
3007 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64);
3009 // If the function takes variable number of arguments, make a frame index for
3010 // the start of the first vararg value... for expansion of llvm.va_start.
3012 int Depth = ArgOffset;
3014 FuncInfo->setVarArgsFrameIndex(
3015 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3017 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3019 // If this function is vararg, store any remaining integer argument regs
3020 // to their spots on the stack so that they may be loaded by deferencing the
3021 // result of va_next.
3022 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3026 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3028 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3030 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3031 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3032 MachinePointerInfo(), false, false, 0);
3033 MemOps.push_back(Store);
3034 // Increment the address by four for the next argument to store
3035 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3036 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3040 if (!MemOps.empty())
3041 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3046 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus
3047 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI.
3049 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
3053 const SmallVectorImpl<ISD::OutputArg>
3055 const SmallVectorImpl<SDValue> &OutVals,
3056 unsigned &nAltivecParamsAtEnd) {
3057 // Count how many bytes are to be pushed on the stack, including the linkage
3058 // area, and parameter passing area. We start with 24/48 bytes, which is
3059 // prereserved space for [SP][CR][LR][3 x unused].
3060 unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
3061 unsigned NumOps = Outs.size();
3062 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3064 // Add up all the space actually used.
3065 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
3066 // they all go in registers, but we must reserve stack space for them for
3067 // possible use by the caller. In varargs or 64-bit calls, parameters are
3068 // assigned stack space in order, with padding so Altivec parameters are
3070 nAltivecParamsAtEnd = 0;
3071 for (unsigned i = 0; i != NumOps; ++i) {
3072 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3073 EVT ArgVT = Outs[i].VT;
3074 // Varargs Altivec parameters are padded to a 16 byte boundary.
3075 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
3076 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8 ||
3077 ArgVT==MVT::v2f64 || ArgVT==MVT::v2i64) {
3078 if (!isVarArg && !isPPC64) {
3079 // Non-varargs Altivec parameters go after all the non-Altivec
3080 // parameters; handle those later so we know how much padding we need.
3081 nAltivecParamsAtEnd++;
3084 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
3085 NumBytes = ((NumBytes+15)/16)*16;
3087 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3090 // Allow for Altivec parameters at the end, if needed.
3091 if (nAltivecParamsAtEnd) {
3092 NumBytes = ((NumBytes+15)/16)*16;
3093 NumBytes += 16*nAltivecParamsAtEnd;
3096 // The prolog code of the callee may store up to 8 GPR argument registers to
3097 // the stack, allowing va_start to index over them in memory if its varargs.
3098 // Because we cannot tell if this is needed on the caller side, we have to
3099 // conservatively assume that it is needed. As such, make sure we have at
3100 // least enough stack space for the caller to store the 8 GPRs.
3101 NumBytes = std::max(NumBytes,
3102 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
3104 // Tail call needs the stack to be aligned.
3105 if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
3106 unsigned TargetAlign = DAG.getMachineFunction().getTarget().
3107 getFrameLowering()->getStackAlignment();
3108 unsigned AlignMask = TargetAlign-1;
3109 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3115 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3116 /// adjusted to accommodate the arguments for the tailcall.
3117 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3118 unsigned ParamSize) {
3120 if (!isTailCall) return 0;
3122 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3123 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3124 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3125 // Remember only if the new adjustement is bigger.
3126 if (SPDiff < FI->getTailCallSPDelta())
3127 FI->setTailCallSPDelta(SPDiff);
3132 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3133 /// for tail call optimization. Targets which want to do tail call
3134 /// optimization should implement this function.
3136 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3137 CallingConv::ID CalleeCC,
3139 const SmallVectorImpl<ISD::InputArg> &Ins,
3140 SelectionDAG& DAG) const {
3141 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3144 // Variable argument functions are not supported.
3148 MachineFunction &MF = DAG.getMachineFunction();
3149 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3150 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3151 // Functions containing by val parameters are not supported.
3152 for (unsigned i = 0; i != Ins.size(); i++) {
3153 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3154 if (Flags.isByVal()) return false;
3157 // Non-PIC/GOT tail calls are supported.
3158 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3161 // At the moment we can only do local tail calls (in same module, hidden
3162 // or protected) if we are generating PIC.
3163 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3164 return G->getGlobal()->hasHiddenVisibility()
3165 || G->getGlobal()->hasProtectedVisibility();
3171 /// isCallCompatibleAddress - Return the immediate to use if the specified
3172 /// 32-bit value is representable in the immediate field of a BxA instruction.
3173 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3174 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3175 if (!C) return nullptr;
3177 int Addr = C->getZExtValue();
3178 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3179 SignExtend32<26>(Addr) != Addr)
3180 return nullptr; // Top 6 bits have to be sext of immediate.
3182 return DAG.getConstant((int)C->getZExtValue() >> 2,
3183 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3188 struct TailCallArgumentInfo {
3193 TailCallArgumentInfo() : FrameIdx(0) {}
3198 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3200 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3202 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3203 SmallVectorImpl<SDValue> &MemOpChains,
3205 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3206 SDValue Arg = TailCallArgs[i].Arg;
3207 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3208 int FI = TailCallArgs[i].FrameIdx;
3209 // Store relative to framepointer.
3210 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3211 MachinePointerInfo::getFixedStack(FI),
3216 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3217 /// the appropriate stack slot for the tail call optimized function call.
3218 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3219 MachineFunction &MF,
3228 // Calculate the new stack slot for the return address.
3229 int SlotSize = isPPC64 ? 8 : 4;
3230 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3232 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3233 NewRetAddrLoc, true);
3234 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3235 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3236 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3237 MachinePointerInfo::getFixedStack(NewRetAddr),
3240 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3241 // slot as the FP is never overwritten.
3244 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3245 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3247 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3248 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3249 MachinePointerInfo::getFixedStack(NewFPIdx),
3256 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3257 /// the position of the argument.
3259 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3260 SDValue Arg, int SPDiff, unsigned ArgOffset,
3261 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3262 int Offset = ArgOffset + SPDiff;
3263 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3264 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3265 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3266 SDValue FIN = DAG.getFrameIndex(FI, VT);
3267 TailCallArgumentInfo Info;
3269 Info.FrameIdxOp = FIN;
3271 TailCallArguments.push_back(Info);
3274 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3275 /// stack slot. Returns the chain as result and the loaded frame pointers in
3276 /// LROpOut/FPOpout. Used when tail calling.
3277 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3285 // Load the LR and FP stack slot for later adjusting.
3286 EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
3287 LROpOut = getReturnAddrFrameIndex(DAG);
3288 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3289 false, false, false, 0);
3290 Chain = SDValue(LROpOut.getNode(), 1);
3292 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3293 // slot as the FP is never overwritten.
3295 FPOpOut = getFramePointerFrameIndex(DAG);
3296 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3297 false, false, false, 0);
3298 Chain = SDValue(FPOpOut.getNode(), 1);
3304 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3305 /// by "Src" to address "Dst" of size "Size". Alignment information is
3306 /// specified by the specific parameter attribute. The copy will be passed as
3307 /// a byval function parameter.
3308 /// Sometimes what we are copying is the end of a larger object, the part that
3309 /// does not fit in registers.
3311 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3312 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3314 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3315 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3316 false, false, MachinePointerInfo(),
3317 MachinePointerInfo());
3320 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3323 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3324 SDValue Arg, SDValue PtrOff, int SPDiff,
3325 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3326 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3327 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3329 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3334 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3336 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3337 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3338 DAG.getConstant(ArgOffset, PtrVT));
3340 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3341 MachinePointerInfo(), false, false, 0));
3342 // Calculate and remember argument location.
3343 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3348 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3349 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3350 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3351 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3352 MachineFunction &MF = DAG.getMachineFunction();
3354 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3355 // might overwrite each other in case of tail call optimization.
3356 SmallVector<SDValue, 8> MemOpChains2;
3357 // Do not flag preceding copytoreg stuff together with the following stuff.
3359 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3361 if (!MemOpChains2.empty())
3362 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3364 // Store the return address to the appropriate stack slot.
3365 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3366 isPPC64, isDarwinABI, dl);
3368 // Emit callseq_end just before tailcall node.
3369 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3370 DAG.getIntPtrConstant(0, true), InFlag, dl);
3371 InFlag = Chain.getValue(1);
3375 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3376 SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3377 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3378 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3379 const PPCSubtarget &PPCSubTarget) {
3381 bool isPPC64 = PPCSubTarget.isPPC64();
3382 bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
3384 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3385 NodeTys.push_back(MVT::Other); // Returns a chain
3386 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3388 unsigned CallOpc = PPCISD::CALL;
3390 bool needIndirectCall = true;
3391 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3392 // If this is an absolute destination address, use the munged value.
3393 Callee = SDValue(Dest, 0);
3394 needIndirectCall = false;
3397 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3398 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3399 // Use indirect calls for ALL functions calls in JIT mode, since the
3400 // far-call stubs may be outside relocation limits for a BL instruction.
3401 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3402 unsigned OpFlags = 0;
3403 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3404 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3405 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3406 (G->getGlobal()->isDeclaration() ||
3407 G->getGlobal()->isWeakForLinker())) {
3408 // PC-relative references to external symbols should go through $stub,
3409 // unless we're building with the leopard linker or later, which
3410 // automatically synthesizes these stubs.
3411 OpFlags = PPCII::MO_DARWIN_STUB;
3414 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3415 // every direct call is) turn it into a TargetGlobalAddress /
3416 // TargetExternalSymbol node so that legalize doesn't hack it.
3417 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3418 Callee.getValueType(),
3420 needIndirectCall = false;
3424 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3425 unsigned char OpFlags = 0;
3427 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3428 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3429 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
3430 // PC-relative references to external symbols should go through $stub,
3431 // unless we're building with the leopard linker or later, which
3432 // automatically synthesizes these stubs.
3433 OpFlags = PPCII::MO_DARWIN_STUB;
3436 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3438 needIndirectCall = false;
3441 if (needIndirectCall) {
3442 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3443 // to do the call, we can't use PPCISD::CALL.
3444 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3446 if (isSVR4ABI && isPPC64) {
3447 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3448 // entry point, but to the function descriptor (the function entry point
3449 // address is part of the function descriptor though).
3450 // The function descriptor is a three doubleword structure with the
3451 // following fields: function entry point, TOC base address and
3452 // environment pointer.
3453 // Thus for a call through a function pointer, the following actions need
3455 // 1. Save the TOC of the caller in the TOC save area of its stack
3456 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3457 // 2. Load the address of the function entry point from the function
3459 // 3. Load the TOC of the callee from the function descriptor into r2.
3460 // 4. Load the environment pointer from the function descriptor into
3462 // 5. Branch to the function entry point address.
3463 // 6. On return of the callee, the TOC of the caller needs to be
3464 // restored (this is done in FinishCall()).
3466 // All those operations are flagged together to ensure that no other
3467 // operations can be scheduled in between. E.g. without flagging the
3468 // operations together, a TOC access in the caller could be scheduled
3469 // between the load of the callee TOC and the branch to the callee, which
3470 // results in the TOC access going through the TOC of the callee instead
3471 // of going through the TOC of the caller, which leads to incorrect code.
3473 // Load the address of the function entry point from the function
3475 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3476 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs,
3477 ArrayRef<SDValue>(MTCTROps, InFlag.getNode() ? 3 : 2));
3478 Chain = LoadFuncPtr.getValue(1);
3479 InFlag = LoadFuncPtr.getValue(2);
3481 // Load environment pointer into r11.
3482 // Offset of the environment pointer within the function descriptor.
3483 SDValue PtrOff = DAG.getIntPtrConstant(16);
3485 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3486 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3488 Chain = LoadEnvPtr.getValue(1);
3489 InFlag = LoadEnvPtr.getValue(2);
3491 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3493 Chain = EnvVal.getValue(0);
3494 InFlag = EnvVal.getValue(1);
3496 // Load TOC of the callee into r2. We are using a target-specific load
3497 // with r2 hard coded, because the result of a target-independent load
3498 // would never go directly into r2, since r2 is a reserved register (which
3499 // prevents the register allocator from allocating it), resulting in an
3500 // additional register being allocated and an unnecessary move instruction
3502 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3503 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3505 Chain = LoadTOCPtr.getValue(0);
3506 InFlag = LoadTOCPtr.getValue(1);
3508 MTCTROps[0] = Chain;
3509 MTCTROps[1] = LoadFuncPtr;
3510 MTCTROps[2] = InFlag;
3513 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3514 ArrayRef<SDValue>(MTCTROps, InFlag.getNode() ? 3 : 2));
3515 InFlag = Chain.getValue(1);
3518 NodeTys.push_back(MVT::Other);
3519 NodeTys.push_back(MVT::Glue);
3520 Ops.push_back(Chain);
3521 CallOpc = PPCISD::BCTRL;
3522 Callee.setNode(nullptr);
3523 // Add use of X11 (holding environment pointer)
3524 if (isSVR4ABI && isPPC64)
3525 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3526 // Add CTR register as callee so a bctr can be emitted later.
3528 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3531 // If this is a direct call, pass the chain and the callee.
3532 if (Callee.getNode()) {
3533 Ops.push_back(Chain);
3534 Ops.push_back(Callee);
3536 // If this is a tail call add stack pointer delta.
3538 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3540 // Add argument registers to the end of the list so that they are known live
3542 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3543 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3544 RegsToPass[i].second.getValueType()));
3550 bool isLocalCall(const SDValue &Callee)
3552 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3553 return !G->getGlobal()->isDeclaration() &&
3554 !G->getGlobal()->isWeakForLinker();
3559 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3560 CallingConv::ID CallConv, bool isVarArg,
3561 const SmallVectorImpl<ISD::InputArg> &Ins,
3562 SDLoc dl, SelectionDAG &DAG,
3563 SmallVectorImpl<SDValue> &InVals) const {
3565 SmallVector<CCValAssign, 16> RVLocs;
3566 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3567 getTargetMachine(), RVLocs, *DAG.getContext());
3568 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3570 // Copy all of the result registers out of their specified physreg.
3571 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3572 CCValAssign &VA = RVLocs[i];
3573 assert(VA.isRegLoc() && "Can only return in registers!");
3575 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3576 VA.getLocReg(), VA.getLocVT(), InFlag);
3577 Chain = Val.getValue(1);
3578 InFlag = Val.getValue(2);
3580 switch (VA.getLocInfo()) {
3581 default: llvm_unreachable("Unknown loc info!");
3582 case CCValAssign::Full: break;
3583 case CCValAssign::AExt:
3584 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3586 case CCValAssign::ZExt:
3587 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3588 DAG.getValueType(VA.getValVT()));
3589 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3591 case CCValAssign::SExt:
3592 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3593 DAG.getValueType(VA.getValVT()));
3594 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3598 InVals.push_back(Val);
3605 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3606 bool isTailCall, bool isVarArg,
3608 SmallVector<std::pair<unsigned, SDValue>, 8>
3610 SDValue InFlag, SDValue Chain,
3612 int SPDiff, unsigned NumBytes,
3613 const SmallVectorImpl<ISD::InputArg> &Ins,
3614 SmallVectorImpl<SDValue> &InVals) const {
3615 std::vector<EVT> NodeTys;
3616 SmallVector<SDValue, 8> Ops;
3617 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3618 isTailCall, RegsToPass, Ops, NodeTys,
3621 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3622 if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
3623 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3625 // When performing tail call optimization the callee pops its arguments off
3626 // the stack. Account for this here so these bytes can be pushed back on in
3627 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3628 int BytesCalleePops =
3629 (CallConv == CallingConv::Fast &&
3630 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3632 // Add a register mask operand representing the call-preserved registers.
3633 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3634 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3635 assert(Mask && "Missing call preserved mask for calling convention");
3636 Ops.push_back(DAG.getRegisterMask(Mask));
3638 if (InFlag.getNode())
3639 Ops.push_back(InFlag);
3643 assert(((Callee.getOpcode() == ISD::Register &&
3644 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3645 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3646 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3647 isa<ConstantSDNode>(Callee)) &&
3648 "Expecting an global address, external symbol, absolute value or register");
3650 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3653 // Add a NOP immediately after the branch instruction when using the 64-bit
3654 // SVR4 ABI. At link time, if caller and callee are in a different module and
3655 // thus have a different TOC, the call will be replaced with a call to a stub
3656 // function which saves the current TOC, loads the TOC of the callee and
3657 // branches to the callee. The NOP will be replaced with a load instruction
3658 // which restores the TOC of the caller from the TOC save slot of the current
3659 // stack frame. If caller and callee belong to the same module (and have the
3660 // same TOC), the NOP will remain unchanged.
3662 bool needsTOCRestore = false;
3663 if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
3664 if (CallOpc == PPCISD::BCTRL) {
3665 // This is a call through a function pointer.
3666 // Restore the caller TOC from the save area into R2.
3667 // See PrepareCall() for more information about calls through function
3668 // pointers in the 64-bit SVR4 ABI.
3669 // We are using a target-specific load with r2 hard coded, because the
3670 // result of a target-independent load would never go directly into r2,
3671 // since r2 is a reserved register (which prevents the register allocator
3672 // from allocating it), resulting in an additional register being
3673 // allocated and an unnecessary move instruction being generated.
3674 needsTOCRestore = true;
3675 } else if ((CallOpc == PPCISD::CALL) &&
3676 (!isLocalCall(Callee) ||
3677 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3678 // Otherwise insert NOP for non-local calls.
3679 CallOpc = PPCISD::CALL_NOP;
3683 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
3684 InFlag = Chain.getValue(1);
3686 if (needsTOCRestore) {
3687 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3688 Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
3689 InFlag = Chain.getValue(1);
3692 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3693 DAG.getIntPtrConstant(BytesCalleePops, true),
3696 InFlag = Chain.getValue(1);
3698 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3699 Ins, dl, DAG, InVals);
3703 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3704 SmallVectorImpl<SDValue> &InVals) const {
3705 SelectionDAG &DAG = CLI.DAG;
3707 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3708 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3709 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3710 SDValue Chain = CLI.Chain;
3711 SDValue Callee = CLI.Callee;
3712 bool &isTailCall = CLI.IsTailCall;
3713 CallingConv::ID CallConv = CLI.CallConv;
3714 bool isVarArg = CLI.IsVarArg;
3717 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3720 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
3721 report_fatal_error("failed to perform tail call elimination on a call "
3722 "site marked musttail");
3724 if (PPCSubTarget.isSVR4ABI()) {
3725 if (PPCSubTarget.isPPC64())
3726 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3727 isTailCall, Outs, OutVals, Ins,
3730 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3731 isTailCall, Outs, OutVals, Ins,
3735 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3736 isTailCall, Outs, OutVals, Ins,
3741 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3742 CallingConv::ID CallConv, bool isVarArg,
3744 const SmallVectorImpl<ISD::OutputArg> &Outs,
3745 const SmallVectorImpl<SDValue> &OutVals,
3746 const SmallVectorImpl<ISD::InputArg> &Ins,
3747 SDLoc dl, SelectionDAG &DAG,
3748 SmallVectorImpl<SDValue> &InVals) const {
3749 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3750 // of the 32-bit SVR4 ABI stack frame layout.
3752 assert((CallConv == CallingConv::C ||
3753 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3755 unsigned PtrByteSize = 4;
3757 MachineFunction &MF = DAG.getMachineFunction();
3759 // Mark this function as potentially containing a function that contains a
3760 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3761 // and restoring the callers stack pointer in this functions epilog. This is
3762 // done because by tail calling the called function might overwrite the value
3763 // in this function's (MF) stack pointer stack slot 0(SP).
3764 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3765 CallConv == CallingConv::Fast)
3766 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3768 // Count how many bytes are to be pushed on the stack, including the linkage
3769 // area, parameter list area and the part of the local variable space which
3770 // contains copies of aggregates which are passed by value.
3772 // Assign locations to all of the outgoing arguments.
3773 SmallVector<CCValAssign, 16> ArgLocs;
3774 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3775 getTargetMachine(), ArgLocs, *DAG.getContext());
3777 // Reserve space for the linkage area on the stack.
3778 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
3781 // Handle fixed and variable vector arguments differently.
3782 // Fixed vector arguments go into registers as long as registers are
3783 // available. Variable vector arguments always go into memory.
3784 unsigned NumArgs = Outs.size();
3786 for (unsigned i = 0; i != NumArgs; ++i) {
3787 MVT ArgVT = Outs[i].VT;
3788 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3791 if (Outs[i].IsFixed) {
3792 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3795 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3801 errs() << "Call operand #" << i << " has unhandled type "
3802 << EVT(ArgVT).getEVTString() << "\n";
3804 llvm_unreachable(0);
3808 // All arguments are treated the same.
3809 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3812 // Assign locations to all of the outgoing aggregate by value arguments.
3813 SmallVector<CCValAssign, 16> ByValArgLocs;
3814 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3815 getTargetMachine(), ByValArgLocs, *DAG.getContext());
3817 // Reserve stack space for the allocations in CCInfo.
3818 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3820 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
3822 // Size of the linkage area, parameter list area and the part of the local
3823 // space variable where copies of aggregates which are passed by value are
3825 unsigned NumBytes = CCByValInfo.getNextStackOffset();
3827 // Calculate by how many bytes the stack has to be adjusted in case of tail
3828 // call optimization.
3829 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3831 // Adjust the stack pointer for the new arguments...
3832 // These operations are automatically eliminated by the prolog/epilog pass
3833 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3835 SDValue CallSeqStart = Chain;
3837 // Load the return address and frame pointer so it can be moved somewhere else
3840 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3843 // Set up a copy of the stack pointer for use loading and storing any
3844 // arguments that may not fit in the registers available for argument
3846 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3848 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3849 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3850 SmallVector<SDValue, 8> MemOpChains;
3852 bool seenFloatArg = false;
3853 // Walk the register/memloc assignments, inserting copies/loads.
3854 for (unsigned i = 0, j = 0, e = ArgLocs.size();
3857 CCValAssign &VA = ArgLocs[i];
3858 SDValue Arg = OutVals[i];
3859 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3861 if (Flags.isByVal()) {
3862 // Argument is an aggregate which is passed by value, thus we need to
3863 // create a copy of it in the local variable space of the current stack
3864 // frame (which is the stack frame of the caller) and pass the address of
3865 // this copy to the callee.
3866 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3867 CCValAssign &ByValVA = ByValArgLocs[j++];
3868 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3870 // Memory reserved in the local variable space of the callers stack frame.
3871 unsigned LocMemOffset = ByValVA.getLocMemOffset();
3873 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3874 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3876 // Create a copy of the argument in the local area of the current
3878 SDValue MemcpyCall =
3879 CreateCopyOfByValArgument(Arg, PtrOff,
3880 CallSeqStart.getNode()->getOperand(0),
3883 // This must go outside the CALLSEQ_START..END.
3884 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3885 CallSeqStart.getNode()->getOperand(1),
3887 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3888 NewCallSeqStart.getNode());
3889 Chain = CallSeqStart = NewCallSeqStart;
3891 // Pass the address of the aggregate copy on the stack either in a
3892 // physical register or in the parameter list area of the current stack
3893 // frame to the callee.
3897 if (VA.isRegLoc()) {
3898 if (Arg.getValueType() == MVT::i1)
3899 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
3901 seenFloatArg |= VA.getLocVT().isFloatingPoint();
3902 // Put argument in a physical register.
3903 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3905 // Put argument in the parameter list area of the current stack frame.
3906 assert(VA.isMemLoc());
3907 unsigned LocMemOffset = VA.getLocMemOffset();
3910 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3911 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3913 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3914 MachinePointerInfo(),
3917 // Calculate and remember argument location.
3918 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3924 if (!MemOpChains.empty())
3925 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3927 // Build a sequence of copy-to-reg nodes chained together with token chain
3928 // and flag operands which copy the outgoing args into the appropriate regs.
3930 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3931 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3932 RegsToPass[i].second, InFlag);
3933 InFlag = Chain.getValue(1);
3936 // Set CR bit 6 to true if this is a vararg call with floating args passed in
3939 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3940 SDValue Ops[] = { Chain, InFlag };
3942 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
3944 ArrayRef<SDValue>(Ops, InFlag.getNode() ? 2 : 1));
3946 InFlag = Chain.getValue(1);
3950 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3951 false, TailCallArguments);
3953 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3954 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3958 // Copy an argument into memory, being careful to do this outside the
3959 // call sequence for the call to which the argument belongs.
3961 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
3962 SDValue CallSeqStart,
3963 ISD::ArgFlagsTy Flags,
3966 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3967 CallSeqStart.getNode()->getOperand(0),
3969 // The MEMCPY must go outside the CALLSEQ_START..END.
3970 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3971 CallSeqStart.getNode()->getOperand(1),
3973 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3974 NewCallSeqStart.getNode());
3975 return NewCallSeqStart;
3979 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
3980 CallingConv::ID CallConv, bool isVarArg,
3982 const SmallVectorImpl<ISD::OutputArg> &Outs,
3983 const SmallVectorImpl<SDValue> &OutVals,
3984 const SmallVectorImpl<ISD::InputArg> &Ins,
3985 SDLoc dl, SelectionDAG &DAG,
3986 SmallVectorImpl<SDValue> &InVals) const {
3988 unsigned NumOps = Outs.size();
3990 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3991 unsigned PtrByteSize = 8;
3993 MachineFunction &MF = DAG.getMachineFunction();
3995 // Mark this function as potentially containing a function that contains a
3996 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3997 // and restoring the callers stack pointer in this functions epilog. This is
3998 // done because by tail calling the called function might overwrite the value
3999 // in this function's (MF) stack pointer stack slot 0(SP).
4000 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4001 CallConv == CallingConv::Fast)
4002 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4004 unsigned nAltivecParamsAtEnd = 0;
4006 // Count how many bytes are to be pushed on the stack, including the linkage
4007 // area, and parameter passing area. We start with at least 48 bytes, which
4008 // is reserved space for [SP][CR][LR][3 x unused].
4009 // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result
4012 CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv,
4013 Outs, OutVals, nAltivecParamsAtEnd);
4015 // Calculate by how many bytes the stack has to be adjusted in case of tail
4016 // call optimization.
4017 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4019 // To protect arguments on the stack from being clobbered in a tail call,
4020 // force all the loads to happen before doing any other lowering.
4022 Chain = DAG.getStackArgumentTokenFactor(Chain);
4024 // Adjust the stack pointer for the new arguments...
4025 // These operations are automatically eliminated by the prolog/epilog pass
4026 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4028 SDValue CallSeqStart = Chain;
4030 // Load the return address and frame pointer so it can be move somewhere else
4033 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4036 // Set up a copy of the stack pointer for use loading and storing any
4037 // arguments that may not fit in the registers available for argument
4039 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4041 // Figure out which arguments are going to go in registers, and which in
4042 // memory. Also, if this is a vararg function, floating point operations
4043 // must be stored to our stack, and loaded into integer regs as well, if
4044 // any integer regs are available for argument passing.
4045 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
4046 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4048 static const MCPhysReg GPR[] = {
4049 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4050 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4052 static const MCPhysReg *FPR = GetFPR();
4054 static const MCPhysReg VR[] = {
4055 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4056 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4058 static const MCPhysReg VSRH[] = {
4059 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4060 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4063 const unsigned NumGPRs = array_lengthof(GPR);
4064 const unsigned NumFPRs = 13;
4065 const unsigned NumVRs = array_lengthof(VR);
4067 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4068 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4070 SmallVector<SDValue, 8> MemOpChains;
4071 for (unsigned i = 0; i != NumOps; ++i) {
4072 SDValue Arg = OutVals[i];
4073 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4075 // PtrOff will be used to store the current argument to the stack if a
4076 // register cannot be found for it.
4079 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4081 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4083 // Promote integers to 64-bit values.
4084 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4085 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4086 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4087 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4090 // FIXME memcpy is used way more than necessary. Correctness first.
4091 // Note: "by value" is code for passing a structure by value, not
4093 if (Flags.isByVal()) {
4094 // Note: Size includes alignment padding, so
4095 // struct x { short a; char b; }
4096 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
4097 // These are the proper values we need for right-justifying the
4098 // aggregate in a parameter register.
4099 unsigned Size = Flags.getByValSize();
4101 // An empty aggregate parameter takes up no storage and no
4106 unsigned BVAlign = Flags.getByValAlign();
4108 if (BVAlign % PtrByteSize != 0)
4110 "ByVal alignment is not a multiple of the pointer size");
4112 ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
4115 // All aggregates smaller than 8 bytes must be passed right-justified.
4116 if (Size==1 || Size==2 || Size==4) {
4117 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4118 if (GPR_idx != NumGPRs) {
4119 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4120 MachinePointerInfo(), VT,
4122 MemOpChains.push_back(Load.getValue(1));
4123 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4125 ArgOffset += PtrByteSize;
4130 if (GPR_idx == NumGPRs && Size < 8) {
4131 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4132 PtrOff.getValueType());
4133 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4134 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4137 ArgOffset += PtrByteSize;
4140 // Copy entire object into memory. There are cases where gcc-generated
4141 // code assumes it is there, even if it could be put entirely into
4142 // registers. (This is not what the doc says.)
4144 // FIXME: The above statement is likely due to a misunderstanding of the
4145 // documents. All arguments must be copied into the parameter area BY
4146 // THE CALLEE in the event that the callee takes the address of any
4147 // formal argument. That has not yet been implemented. However, it is
4148 // reasonable to use the stack area as a staging area for the register
4151 // Skip this for small aggregates, as we will use the same slot for a
4152 // right-justified copy, below.
4154 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4158 // When a register is available, pass a small aggregate right-justified.
4159 if (Size < 8 && GPR_idx != NumGPRs) {
4160 // The easiest way to get this right-justified in a register
4161 // is to copy the structure into the rightmost portion of a
4162 // local variable slot, then load the whole slot into the
4164 // FIXME: The memcpy seems to produce pretty awful code for
4165 // small aggregates, particularly for packed ones.
4166 // FIXME: It would be preferable to use the slot in the
4167 // parameter save area instead of a new local variable.
4168 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4169 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4170 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4174 // Load the slot into the register.
4175 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4176 MachinePointerInfo(),
4177 false, false, false, 0);
4178 MemOpChains.push_back(Load.getValue(1));
4179 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4181 // Done with this argument.
4182 ArgOffset += PtrByteSize;
4186 // For aggregates larger than PtrByteSize, copy the pieces of the
4187 // object that fit into registers from the parameter save area.
4188 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4189 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4190 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4191 if (GPR_idx != NumGPRs) {
4192 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4193 MachinePointerInfo(),
4194 false, false, false, 0);
4195 MemOpChains.push_back(Load.getValue(1));
4196 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4197 ArgOffset += PtrByteSize;
4199 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4206 switch (Arg.getSimpleValueType().SimpleTy) {
4207 default: llvm_unreachable("Unexpected ValueType for argument!");
4211 if (GPR_idx != NumGPRs) {
4212 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4214 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4215 true, isTailCall, false, MemOpChains,
4216 TailCallArguments, dl);
4218 ArgOffset += PtrByteSize;
4222 if (FPR_idx != NumFPRs) {
4223 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4226 // A single float or an aggregate containing only a single float
4227 // must be passed right-justified in the stack doubleword, and
4228 // in the GPR, if one is available.
4230 if (Arg.getSimpleValueType().SimpleTy == MVT::f32) {
4231 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4232 StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4236 SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
4237 MachinePointerInfo(), false, false, 0);
4238 MemOpChains.push_back(Store);
4240 // Float varargs are always shadowed in available integer registers
4241 if (GPR_idx != NumGPRs) {
4242 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4243 MachinePointerInfo(), false, false,
4245 MemOpChains.push_back(Load.getValue(1));
4246 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4248 } else if (GPR_idx != NumGPRs)
4249 // If we have any FPRs remaining, we may also have GPRs remaining.
4252 // Single-precision floating-point values are mapped to the
4253 // second (rightmost) word of the stack doubleword.
4254 if (Arg.getValueType() == MVT::f32) {
4255 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4256 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4259 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4260 true, isTailCall, false, MemOpChains,
4261 TailCallArguments, dl);
4272 // These go aligned on the stack, or in the corresponding R registers
4273 // when within range. The Darwin PPC ABI doc claims they also go in
4274 // V registers; in fact gcc does this only for arguments that are
4275 // prototyped, not for those that match the ... We do it for all
4276 // arguments, seems to work.
4277 while (ArgOffset % 16 !=0) {
4278 ArgOffset += PtrByteSize;
4279 if (GPR_idx != NumGPRs)
4282 // We could elide this store in the case where the object fits
4283 // entirely in R registers. Maybe later.
4284 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4285 DAG.getConstant(ArgOffset, PtrVT));
4286 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4287 MachinePointerInfo(), false, false, 0);
4288 MemOpChains.push_back(Store);
4289 if (VR_idx != NumVRs) {
4290 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4291 MachinePointerInfo(),
4292 false, false, false, 0);
4293 MemOpChains.push_back(Load.getValue(1));
4295 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4296 Arg.getSimpleValueType() == MVT::v2i64) ?
4297 VSRH[VR_idx] : VR[VR_idx];
4300 RegsToPass.push_back(std::make_pair(VReg, Load));
4303 for (unsigned i=0; i<16; i+=PtrByteSize) {
4304 if (GPR_idx == NumGPRs)
4306 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4307 DAG.getConstant(i, PtrVT));
4308 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4309 false, false, false, 0);
4310 MemOpChains.push_back(Load.getValue(1));
4311 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4316 // Non-varargs Altivec params generally go in registers, but have
4317 // stack space allocated at the end.
4318 if (VR_idx != NumVRs) {
4319 // Doesn't have GPR space allocated.
4320 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4321 Arg.getSimpleValueType() == MVT::v2i64) ?
4322 VSRH[VR_idx] : VR[VR_idx];
4325 RegsToPass.push_back(std::make_pair(VReg, Arg));
4327 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4328 true, isTailCall, true, MemOpChains,
4329 TailCallArguments, dl);
4336 if (!MemOpChains.empty())
4337 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4339 // Check if this is an indirect call (MTCTR/BCTRL).
4340 // See PrepareCall() for more information about calls through function
4341 // pointers in the 64-bit SVR4 ABI.
4343 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4344 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4345 !isBLACompatibleAddress(Callee, DAG)) {
4346 // Load r2 into a virtual register and store it to the TOC save area.
4347 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4348 // TOC save area offset.
4349 SDValue PtrOff = DAG.getIntPtrConstant(40);
4350 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4351 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4353 // R12 must contain the address of an indirect callee. This does not
4354 // mean the MTCTR instruction must use R12; it's easier to model this
4355 // as an extra parameter, so do that.
4356 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4359 // Build a sequence of copy-to-reg nodes chained together with token chain
4360 // and flag operands which copy the outgoing args into the appropriate regs.
4362 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4363 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4364 RegsToPass[i].second, InFlag);
4365 InFlag = Chain.getValue(1);
4369 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4370 FPOp, true, TailCallArguments);
4372 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4373 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4378 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4379 CallingConv::ID CallConv, bool isVarArg,
4381 const SmallVectorImpl<ISD::OutputArg> &Outs,
4382 const SmallVectorImpl<SDValue> &OutVals,
4383 const SmallVectorImpl<ISD::InputArg> &Ins,
4384 SDLoc dl, SelectionDAG &DAG,
4385 SmallVectorImpl<SDValue> &InVals) const {
4387 unsigned NumOps = Outs.size();
4389 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4390 bool isPPC64 = PtrVT == MVT::i64;
4391 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4393 MachineFunction &MF = DAG.getMachineFunction();
4395 // Mark this function as potentially containing a function that contains a
4396 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4397 // and restoring the callers stack pointer in this functions epilog. This is
4398 // done because by tail calling the called function might overwrite the value
4399 // in this function's (MF) stack pointer stack slot 0(SP).
4400 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4401 CallConv == CallingConv::Fast)
4402 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4404 unsigned nAltivecParamsAtEnd = 0;
4406 // Count how many bytes are to be pushed on the stack, including the linkage
4407 // area, and parameter passing area. We start with 24/48 bytes, which is
4408 // prereserved space for [SP][CR][LR][3 x unused].
4410 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
4412 nAltivecParamsAtEnd);
4414 // Calculate by how many bytes the stack has to be adjusted in case of tail
4415 // call optimization.
4416 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4418 // To protect arguments on the stack from being clobbered in a tail call,
4419 // force all the loads to happen before doing any other lowering.
4421 Chain = DAG.getStackArgumentTokenFactor(Chain);
4423 // Adjust the stack pointer for the new arguments...
4424 // These operations are automatically eliminated by the prolog/epilog pass
4425 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4427 SDValue CallSeqStart = Chain;
4429 // Load the return address and frame pointer so it can be move somewhere else
4432 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4435 // Set up a copy of the stack pointer for use loading and storing any
4436 // arguments that may not fit in the registers available for argument
4440 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4442 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4444 // Figure out which arguments are going to go in registers, and which in
4445 // memory. Also, if this is a vararg function, floating point operations
4446 // must be stored to our stack, and loaded into integer regs as well, if
4447 // any integer regs are available for argument passing.
4448 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
4449 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4451 static const MCPhysReg GPR_32[] = { // 32-bit registers.
4452 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4453 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4455 static const MCPhysReg GPR_64[] = { // 64-bit registers.
4456 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4457 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4459 static const MCPhysReg *FPR = GetFPR();
4461 static const MCPhysReg VR[] = {
4462 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4463 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4465 const unsigned NumGPRs = array_lengthof(GPR_32);
4466 const unsigned NumFPRs = 13;
4467 const unsigned NumVRs = array_lengthof(VR);
4469 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4471 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4472 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4474 SmallVector<SDValue, 8> MemOpChains;
4475 for (unsigned i = 0; i != NumOps; ++i) {
4476 SDValue Arg = OutVals[i];
4477 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4479 // PtrOff will be used to store the current argument to the stack if a
4480 // register cannot be found for it.
4483 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4485 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4487 // On PPC64, promote integers to 64-bit values.
4488 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4489 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4490 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4491 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4494 // FIXME memcpy is used way more than necessary. Correctness first.
4495 // Note: "by value" is code for passing a structure by value, not
4497 if (Flags.isByVal()) {
4498 unsigned Size = Flags.getByValSize();
4499 // Very small objects are passed right-justified. Everything else is
4500 // passed left-justified.
4501 if (Size==1 || Size==2) {
4502 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4503 if (GPR_idx != NumGPRs) {
4504 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4505 MachinePointerInfo(), VT,
4507 MemOpChains.push_back(Load.getValue(1));
4508 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4510 ArgOffset += PtrByteSize;
4512 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4513 PtrOff.getValueType());
4514 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4515 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4518 ArgOffset += PtrByteSize;
4522 // Copy entire object into memory. There are cases where gcc-generated
4523 // code assumes it is there, even if it could be put entirely into
4524 // registers. (This is not what the doc says.)
4525 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4529 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4530 // copy the pieces of the object that fit into registers from the
4531 // parameter save area.
4532 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4533 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4534 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4535 if (GPR_idx != NumGPRs) {
4536 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4537 MachinePointerInfo(),
4538 false, false, false, 0);
4539 MemOpChains.push_back(Load.getValue(1));
4540 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4541 ArgOffset += PtrByteSize;
4543 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4550 switch (Arg.getSimpleValueType().SimpleTy) {
4551 default: llvm_unreachable("Unexpected ValueType for argument!");
4555 if (GPR_idx != NumGPRs) {
4556 if (Arg.getValueType() == MVT::i1)
4557 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4559 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4561 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4562 isPPC64, isTailCall, false, MemOpChains,
4563 TailCallArguments, dl);
4565 ArgOffset += PtrByteSize;
4569 if (FPR_idx != NumFPRs) {
4570 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4573 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4574 MachinePointerInfo(), false, false, 0);
4575 MemOpChains.push_back(Store);
4577 // Float varargs are always shadowed in available integer registers
4578 if (GPR_idx != NumGPRs) {
4579 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4580 MachinePointerInfo(), false, false,
4582 MemOpChains.push_back(Load.getValue(1));
4583 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4585 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4586 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4587 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4588 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4589 MachinePointerInfo(),
4590 false, false, false, 0);
4591 MemOpChains.push_back(Load.getValue(1));
4592 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4595 // If we have any FPRs remaining, we may also have GPRs remaining.
4596 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4598 if (GPR_idx != NumGPRs)
4600 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4601 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4605 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4606 isPPC64, isTailCall, false, MemOpChains,
4607 TailCallArguments, dl);
4611 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4618 // These go aligned on the stack, or in the corresponding R registers
4619 // when within range. The Darwin PPC ABI doc claims they also go in
4620 // V registers; in fact gcc does this only for arguments that are
4621 // prototyped, not for those that match the ... We do it for all
4622 // arguments, seems to work.
4623 while (ArgOffset % 16 !=0) {
4624 ArgOffset += PtrByteSize;
4625 if (GPR_idx != NumGPRs)
4628 // We could elide this store in the case where the object fits
4629 // entirely in R registers. Maybe later.
4630 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4631 DAG.getConstant(ArgOffset, PtrVT));
4632 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4633 MachinePointerInfo(), false, false, 0);
4634 MemOpChains.push_back(Store);
4635 if (VR_idx != NumVRs) {
4636 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4637 MachinePointerInfo(),
4638 false, false, false, 0);
4639 MemOpChains.push_back(Load.getValue(1));
4640 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4643 for (unsigned i=0; i<16; i+=PtrByteSize) {
4644 if (GPR_idx == NumGPRs)
4646 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4647 DAG.getConstant(i, PtrVT));
4648 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4649 false, false, false, 0);
4650 MemOpChains.push_back(Load.getValue(1));
4651 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4656 // Non-varargs Altivec params generally go in registers, but have
4657 // stack space allocated at the end.
4658 if (VR_idx != NumVRs) {
4659 // Doesn't have GPR space allocated.
4660 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4661 } else if (nAltivecParamsAtEnd==0) {
4662 // We are emitting Altivec params in order.
4663 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4664 isPPC64, isTailCall, true, MemOpChains,
4665 TailCallArguments, dl);
4671 // If all Altivec parameters fit in registers, as they usually do,
4672 // they get stack space following the non-Altivec parameters. We
4673 // don't track this here because nobody below needs it.
4674 // If there are more Altivec parameters than fit in registers emit
4676 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4678 // Offset is aligned; skip 1st 12 params which go in V registers.
4679 ArgOffset = ((ArgOffset+15)/16)*16;
4681 for (unsigned i = 0; i != NumOps; ++i) {
4682 SDValue Arg = OutVals[i];
4683 EVT ArgType = Outs[i].VT;
4684 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4685 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4688 // We are emitting Altivec params in order.
4689 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4690 isPPC64, isTailCall, true, MemOpChains,
4691 TailCallArguments, dl);
4698 if (!MemOpChains.empty())
4699 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4701 // On Darwin, R12 must contain the address of an indirect callee. This does
4702 // not mean the MTCTR instruction must use R12; it's easier to model this as
4703 // an extra parameter, so do that.
4705 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4706 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4707 !isBLACompatibleAddress(Callee, DAG))
4708 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4709 PPC::R12), Callee));
4711 // Build a sequence of copy-to-reg nodes chained together with token chain
4712 // and flag operands which copy the outgoing args into the appropriate regs.
4714 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4715 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4716 RegsToPass[i].second, InFlag);
4717 InFlag = Chain.getValue(1);
4721 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4722 FPOp, true, TailCallArguments);
4724 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4725 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4730 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4731 MachineFunction &MF, bool isVarArg,
4732 const SmallVectorImpl<ISD::OutputArg> &Outs,
4733 LLVMContext &Context) const {
4734 SmallVector<CCValAssign, 16> RVLocs;
4735 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4737 return CCInfo.CheckReturn(Outs, RetCC_PPC);
4741 PPCTargetLowering::LowerReturn(SDValue Chain,
4742 CallingConv::ID CallConv, bool isVarArg,
4743 const SmallVectorImpl<ISD::OutputArg> &Outs,
4744 const SmallVectorImpl<SDValue> &OutVals,
4745 SDLoc dl, SelectionDAG &DAG) const {
4747 SmallVector<CCValAssign, 16> RVLocs;
4748 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4749 getTargetMachine(), RVLocs, *DAG.getContext());
4750 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4753 SmallVector<SDValue, 4> RetOps(1, Chain);
4755 // Copy the result values into the output registers.
4756 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4757 CCValAssign &VA = RVLocs[i];
4758 assert(VA.isRegLoc() && "Can only return in registers!");
4760 SDValue Arg = OutVals[i];
4762 switch (VA.getLocInfo()) {
4763 default: llvm_unreachable("Unknown loc info!");
4764 case CCValAssign::Full: break;
4765 case CCValAssign::AExt:
4766 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4768 case CCValAssign::ZExt:
4769 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4771 case CCValAssign::SExt:
4772 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4776 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4777 Flag = Chain.getValue(1);
4778 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4781 RetOps[0] = Chain; // Update chain.
4783 // Add the flag if we have it.
4785 RetOps.push_back(Flag);
4787 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
4790 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4791 const PPCSubtarget &Subtarget) const {
4792 // When we pop the dynamic allocation we need to restore the SP link.
4795 // Get the corect type for pointers.
4796 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4798 // Construct the stack pointer operand.
4799 bool isPPC64 = Subtarget.isPPC64();
4800 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4801 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4803 // Get the operands for the STACKRESTORE.
4804 SDValue Chain = Op.getOperand(0);
4805 SDValue SaveSP = Op.getOperand(1);
4807 // Load the old link SP.
4808 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4809 MachinePointerInfo(),
4810 false, false, false, 0);
4812 // Restore the stack pointer.
4813 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4815 // Store the old link SP.
4816 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4823 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4824 MachineFunction &MF = DAG.getMachineFunction();
4825 bool isPPC64 = PPCSubTarget.isPPC64();
4826 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4827 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4829 // Get current frame pointer save index. The users of this index will be
4830 // primarily DYNALLOC instructions.
4831 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4832 int RASI = FI->getReturnAddrSaveIndex();
4834 // If the frame pointer save index hasn't been defined yet.
4836 // Find out what the fix offset of the frame pointer save area.
4837 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4838 // Allocate the frame index for frame pointer save area.
4839 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4841 FI->setReturnAddrSaveIndex(RASI);
4843 return DAG.getFrameIndex(RASI, PtrVT);
4847 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
4848 MachineFunction &MF = DAG.getMachineFunction();
4849 bool isPPC64 = PPCSubTarget.isPPC64();
4850 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4851 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4853 // Get current frame pointer save index. The users of this index will be
4854 // primarily DYNALLOC instructions.
4855 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4856 int FPSI = FI->getFramePointerSaveIndex();
4858 // If the frame pointer save index hasn't been defined yet.
4860 // Find out what the fix offset of the frame pointer save area.
4861 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
4864 // Allocate the frame index for frame pointer save area.
4865 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
4867 FI->setFramePointerSaveIndex(FPSI);
4869 return DAG.getFrameIndex(FPSI, PtrVT);
4872 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4874 const PPCSubtarget &Subtarget) const {
4876 SDValue Chain = Op.getOperand(0);
4877 SDValue Size = Op.getOperand(1);
4880 // Get the corect type for pointers.
4881 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4883 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
4884 DAG.getConstant(0, PtrVT), Size);
4885 // Construct a node for the frame pointer save index.
4886 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
4887 // Build a DYNALLOC node.
4888 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
4889 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
4890 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
4893 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
4894 SelectionDAG &DAG) const {
4896 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
4897 DAG.getVTList(MVT::i32, MVT::Other),
4898 Op.getOperand(0), Op.getOperand(1));
4901 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
4902 SelectionDAG &DAG) const {
4904 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
4905 Op.getOperand(0), Op.getOperand(1));
4908 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
4909 assert(Op.getValueType() == MVT::i1 &&
4910 "Custom lowering only for i1 loads");
4912 // First, load 8 bits into 32 bits, then truncate to 1 bit.
4915 LoadSDNode *LD = cast<LoadSDNode>(Op);
4917 SDValue Chain = LD->getChain();
4918 SDValue BasePtr = LD->getBasePtr();
4919 MachineMemOperand *MMO = LD->getMemOperand();
4921 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
4922 BasePtr, MVT::i8, MMO);
4923 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
4925 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
4926 return DAG.getMergeValues(Ops, 2, dl);
4929 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
4930 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
4931 "Custom lowering only for i1 stores");
4933 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
4936 StoreSDNode *ST = cast<StoreSDNode>(Op);
4938 SDValue Chain = ST->getChain();
4939 SDValue BasePtr = ST->getBasePtr();
4940 SDValue Value = ST->getValue();
4941 MachineMemOperand *MMO = ST->getMemOperand();
4943 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
4944 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
4947 // FIXME: Remove this once the ANDI glue bug is fixed:
4948 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
4949 assert(Op.getValueType() == MVT::i1 &&
4950 "Custom lowering only for i1 results");
4953 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
4957 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
4959 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4960 // Not FP? Not a fsel.
4961 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
4962 !Op.getOperand(2).getValueType().isFloatingPoint())
4965 // We might be able to do better than this under some circumstances, but in
4966 // general, fsel-based lowering of select is a finite-math-only optimization.
4967 // For more information, see section F.3 of the 2.06 ISA specification.
4968 if (!DAG.getTarget().Options.NoInfsFPMath ||
4969 !DAG.getTarget().Options.NoNaNsFPMath)
4972 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4974 EVT ResVT = Op.getValueType();
4975 EVT CmpVT = Op.getOperand(0).getValueType();
4976 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4977 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
4980 // If the RHS of the comparison is a 0.0, we don't need to do the
4981 // subtraction at all.
4983 if (isFloatingPointZero(RHS))
4985 default: break; // SETUO etc aren't handled by fsel.
4989 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4990 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4991 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4992 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
4993 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4994 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4995 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
4998 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5001 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5002 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5003 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5006 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5009 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5010 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5011 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5012 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5017 default: break; // SETUO etc aren't handled by fsel.
5021 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5022 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5023 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5024 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5025 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5026 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5027 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5028 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5031 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5032 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5033 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5034 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5037 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5038 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5039 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5040 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5043 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5044 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5045 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5046 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5049 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5050 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5051 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5052 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5057 // FIXME: Split this code up when LegalizeDAGTypes lands.
5058 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5060 assert(Op.getOperand(0).getValueType().isFloatingPoint());
5061 SDValue Src = Op.getOperand(0);
5062 if (Src.getValueType() == MVT::f32)
5063 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5066 switch (Op.getSimpleValueType().SimpleTy) {
5067 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5069 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
5070 (PPCSubTarget.hasFPCVT() ? PPCISD::FCTIWUZ :
5075 assert((Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT()) &&
5076 "i64 FP_TO_UINT is supported only with FPCVT");
5077 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5083 // Convert the FP value to an int value through memory.
5084 bool i32Stack = Op.getValueType() == MVT::i32 && PPCSubTarget.hasSTFIWX() &&
5085 (Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT());
5086 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5087 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5088 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5090 // Emit a store to the stack slot.
5093 MachineFunction &MF = DAG.getMachineFunction();
5094 MachineMemOperand *MMO =
5095 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5096 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5097 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5098 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
5101 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5102 MPI, false, false, 0);
5104 // Result is a load from the stack slot. If loading 4 bytes, make sure to
5106 if (Op.getValueType() == MVT::i32 && !i32Stack) {
5107 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5108 DAG.getConstant(4, FIPtr.getValueType()));
5109 MPI = MachinePointerInfo();
5112 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
5113 false, false, false, 0);
5116 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5117 SelectionDAG &DAG) const {
5119 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5120 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5123 if (Op.getOperand(0).getValueType() == MVT::i1)
5124 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5125 DAG.getConstantFP(1.0, Op.getValueType()),
5126 DAG.getConstantFP(0.0, Op.getValueType()));
5128 assert((Op.getOpcode() == ISD::SINT_TO_FP || PPCSubTarget.hasFPCVT()) &&
5129 "UINT_TO_FP is supported only with FPCVT");
5131 // If we have FCFIDS, then use it when converting to single-precision.
5132 // Otherwise, convert to double-precision and then round.
5133 unsigned FCFOp = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5134 (Op.getOpcode() == ISD::UINT_TO_FP ?
5135 PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5136 (Op.getOpcode() == ISD::UINT_TO_FP ?
5137 PPCISD::FCFIDU : PPCISD::FCFID);
5138 MVT FCFTy = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5139 MVT::f32 : MVT::f64;
5141 if (Op.getOperand(0).getValueType() == MVT::i64) {
5142 SDValue SINT = Op.getOperand(0);
5143 // When converting to single-precision, we actually need to convert
5144 // to double-precision first and then round to single-precision.
5145 // To avoid double-rounding effects during that operation, we have
5146 // to prepare the input operand. Bits that might be truncated when
5147 // converting to double-precision are replaced by a bit that won't
5148 // be lost at this stage, but is below the single-precision rounding
5151 // However, if -enable-unsafe-fp-math is in effect, accept double
5152 // rounding to avoid the extra overhead.
5153 if (Op.getValueType() == MVT::f32 &&
5154 !PPCSubTarget.hasFPCVT() &&
5155 !DAG.getTarget().Options.UnsafeFPMath) {
5157 // Twiddle input to make sure the low 11 bits are zero. (If this
5158 // is the case, we are guaranteed the value will fit into the 53 bit
5159 // mantissa of an IEEE double-precision value without rounding.)
5160 // If any of those low 11 bits were not zero originally, make sure
5161 // bit 12 (value 2048) is set instead, so that the final rounding
5162 // to single-precision gets the correct result.
5163 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5164 SINT, DAG.getConstant(2047, MVT::i64));
5165 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5166 Round, DAG.getConstant(2047, MVT::i64));
5167 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5168 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5169 Round, DAG.getConstant(-2048, MVT::i64));
5171 // However, we cannot use that value unconditionally: if the magnitude
5172 // of the input value is small, the bit-twiddling we did above might
5173 // end up visibly changing the output. Fortunately, in that case, we
5174 // don't need to twiddle bits since the original input will convert
5175 // exactly to double-precision floating-point already. Therefore,
5176 // construct a conditional to use the original value if the top 11
5177 // bits are all sign-bit copies, and use the rounded value computed
5179 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5180 SINT, DAG.getConstant(53, MVT::i32));
5181 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5182 Cond, DAG.getConstant(1, MVT::i64));
5183 Cond = DAG.getSetCC(dl, MVT::i32,
5184 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5186 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5189 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5190 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5192 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5193 FP = DAG.getNode(ISD::FP_ROUND, dl,
5194 MVT::f32, FP, DAG.getIntPtrConstant(0));
5198 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5199 "Unhandled INT_TO_FP type in custom expander!");
5200 // Since we only generate this in 64-bit mode, we can take advantage of
5201 // 64-bit registers. In particular, sign extend the input value into the
5202 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5203 // then lfd it and fcfid it.
5204 MachineFunction &MF = DAG.getMachineFunction();
5205 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5206 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5209 if (PPCSubTarget.hasLFIWAX() || PPCSubTarget.hasFPCVT()) {
5210 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5211 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5213 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5214 MachinePointerInfo::getFixedStack(FrameIdx),
5217 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5218 "Expected an i32 store");
5219 MachineMemOperand *MMO =
5220 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
5221 MachineMemOperand::MOLoad, 4, 4);
5222 SDValue Ops[] = { Store, FIdx };
5223 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5224 PPCISD::LFIWZX : PPCISD::LFIWAX,
5225 dl, DAG.getVTList(MVT::f64, MVT::Other),
5226 Ops, 2, MVT::i32, MMO);
5228 assert(PPCSubTarget.isPPC64() &&
5229 "i32->FP without LFIWAX supported only on PPC64");
5231 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5232 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5234 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5237 // STD the extended value into the stack slot.
5238 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5239 MachinePointerInfo::getFixedStack(FrameIdx),
5242 // Load the value as a double.
5243 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5244 MachinePointerInfo::getFixedStack(FrameIdx),
5245 false, false, false, 0);
5248 // FCFID it and return it.
5249 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5250 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5251 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5255 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5256 SelectionDAG &DAG) const {
5259 The rounding mode is in bits 30:31 of FPSR, and has the following
5266 FLT_ROUNDS, on the other hand, expects the following:
5273 To perform the conversion, we do:
5274 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5277 MachineFunction &MF = DAG.getMachineFunction();
5278 EVT VT = Op.getValueType();
5279 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5281 // Save FP Control Word to register
5283 MVT::f64, // return register
5284 MVT::Glue // unused in this context
5286 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, ArrayRef<SDValue>());
5288 // Save FP register to stack slot
5289 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5290 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5291 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5292 StackSlot, MachinePointerInfo(), false, false,0);
5294 // Load FP Control Word from low 32 bits of stack slot.
5295 SDValue Four = DAG.getConstant(4, PtrVT);
5296 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5297 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5298 false, false, false, 0);
5300 // Transform as necessary
5302 DAG.getNode(ISD::AND, dl, MVT::i32,
5303 CWD, DAG.getConstant(3, MVT::i32));
5305 DAG.getNode(ISD::SRL, dl, MVT::i32,
5306 DAG.getNode(ISD::AND, dl, MVT::i32,
5307 DAG.getNode(ISD::XOR, dl, MVT::i32,
5308 CWD, DAG.getConstant(3, MVT::i32)),
5309 DAG.getConstant(3, MVT::i32)),
5310 DAG.getConstant(1, MVT::i32));
5313 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5315 return DAG.getNode((VT.getSizeInBits() < 16 ?
5316 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5319 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5320 EVT VT = Op.getValueType();
5321 unsigned BitWidth = VT.getSizeInBits();
5323 assert(Op.getNumOperands() == 3 &&
5324 VT == Op.getOperand(1).getValueType() &&
5327 // Expand into a bunch of logical ops. Note that these ops
5328 // depend on the PPC behavior for oversized shift amounts.
5329 SDValue Lo = Op.getOperand(0);
5330 SDValue Hi = Op.getOperand(1);
5331 SDValue Amt = Op.getOperand(2);
5332 EVT AmtVT = Amt.getValueType();
5334 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5335 DAG.getConstant(BitWidth, AmtVT), Amt);
5336 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5337 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5338 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5339 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5340 DAG.getConstant(-BitWidth, AmtVT));
5341 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5342 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5343 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5344 SDValue OutOps[] = { OutLo, OutHi };
5345 return DAG.getMergeValues(OutOps, 2, dl);
5348 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5349 EVT VT = Op.getValueType();
5351 unsigned BitWidth = VT.getSizeInBits();
5352 assert(Op.getNumOperands() == 3 &&
5353 VT == Op.getOperand(1).getValueType() &&
5356 // Expand into a bunch of logical ops. Note that these ops
5357 // depend on the PPC behavior for oversized shift amounts.
5358 SDValue Lo = Op.getOperand(0);
5359 SDValue Hi = Op.getOperand(1);
5360 SDValue Amt = Op.getOperand(2);
5361 EVT AmtVT = Amt.getValueType();
5363 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5364 DAG.getConstant(BitWidth, AmtVT), Amt);
5365 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5366 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5367 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5368 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5369 DAG.getConstant(-BitWidth, AmtVT));
5370 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5371 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5372 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5373 SDValue OutOps[] = { OutLo, OutHi };
5374 return DAG.getMergeValues(OutOps, 2, dl);
5377 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5379 EVT VT = Op.getValueType();
5380 unsigned BitWidth = VT.getSizeInBits();
5381 assert(Op.getNumOperands() == 3 &&
5382 VT == Op.getOperand(1).getValueType() &&
5385 // Expand into a bunch of logical ops, followed by a select_cc.
5386 SDValue Lo = Op.getOperand(0);
5387 SDValue Hi = Op.getOperand(1);
5388 SDValue Amt = Op.getOperand(2);
5389 EVT AmtVT = Amt.getValueType();
5391 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5392 DAG.getConstant(BitWidth, AmtVT), Amt);
5393 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5394 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5395 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5396 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5397 DAG.getConstant(-BitWidth, AmtVT));
5398 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5399 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5400 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5401 Tmp4, Tmp6, ISD::SETLE);
5402 SDValue OutOps[] = { OutLo, OutHi };
5403 return DAG.getMergeValues(OutOps, 2, dl);
5406 //===----------------------------------------------------------------------===//
5407 // Vector related lowering.
5410 /// BuildSplatI - Build a canonical splati of Val with an element size of
5411 /// SplatSize. Cast the result to VT.
5412 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5413 SelectionDAG &DAG, SDLoc dl) {
5414 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5416 static const EVT VTys[] = { // canonical VT to use for each size.
5417 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5420 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5422 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5426 EVT CanonicalVT = VTys[SplatSize-1];
5428 // Build a canonical splat for this value.
5429 SDValue Elt = DAG.getConstant(Val, MVT::i32);
5430 SmallVector<SDValue, 8> Ops;
5431 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5432 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
5433 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5436 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5437 /// specified intrinsic ID.
5438 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5439 SelectionDAG &DAG, SDLoc dl,
5440 EVT DestVT = MVT::Other) {
5441 if (DestVT == MVT::Other) DestVT = Op.getValueType();
5442 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5443 DAG.getConstant(IID, MVT::i32), Op);
5446 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5447 /// specified intrinsic ID.
5448 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5449 SelectionDAG &DAG, SDLoc dl,
5450 EVT DestVT = MVT::Other) {
5451 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5452 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5453 DAG.getConstant(IID, MVT::i32), LHS, RHS);
5456 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5457 /// specified intrinsic ID.
5458 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5459 SDValue Op2, SelectionDAG &DAG,
5460 SDLoc dl, EVT DestVT = MVT::Other) {
5461 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5462 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5463 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5467 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5468 /// amount. The result has the specified value type.
5469 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5470 EVT VT, SelectionDAG &DAG, SDLoc dl) {
5471 // Force LHS/RHS to be the right type.
5472 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5473 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5476 for (unsigned i = 0; i != 16; ++i)
5478 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5479 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5482 // If this is a case we can't handle, return null and let the default
5483 // expansion code take care of it. If we CAN select this case, and if it
5484 // selects to a single instruction, return Op. Otherwise, if we can codegen
5485 // this case more efficiently than a constant pool load, lower it to the
5486 // sequence of ops that should be used.
5487 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5488 SelectionDAG &DAG) const {
5490 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5491 assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5493 // Check if this is a splat of a constant value.
5494 APInt APSplatBits, APSplatUndef;
5495 unsigned SplatBitSize;
5497 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5498 HasAnyUndefs, 0, true) || SplatBitSize > 32)
5501 unsigned SplatBits = APSplatBits.getZExtValue();
5502 unsigned SplatUndef = APSplatUndef.getZExtValue();
5503 unsigned SplatSize = SplatBitSize / 8;
5505 // First, handle single instruction cases.
5508 if (SplatBits == 0) {
5509 // Canonicalize all zero vectors to be v4i32.
5510 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5511 SDValue Z = DAG.getConstant(0, MVT::i32);
5512 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5513 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5518 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5519 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5521 if (SextVal >= -16 && SextVal <= 15)
5522 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5525 // Two instruction sequences.
5527 // If this value is in the range [-32,30] and is even, use:
5528 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5529 // If this value is in the range [17,31] and is odd, use:
5530 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5531 // If this value is in the range [-31,-17] and is odd, use:
5532 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5533 // Note the last two are three-instruction sequences.
5534 if (SextVal >= -32 && SextVal <= 31) {
5535 // To avoid having these optimizations undone by constant folding,
5536 // we convert to a pseudo that will be expanded later into one of
5538 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5539 EVT VT = Op.getValueType();
5540 int Size = VT == MVT::v16i8 ? 1 : (VT == MVT::v8i16 ? 2 : 4);
5541 SDValue EltSize = DAG.getConstant(Size, MVT::i32);
5542 return DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5545 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
5546 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
5548 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5549 // Make -1 and vspltisw -1:
5550 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5552 // Make the VSLW intrinsic, computing 0x8000_0000.
5553 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5556 // xor by OnesV to invert it.
5557 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5558 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5561 // Check to see if this is a wide variety of vsplti*, binop self cases.
5562 static const signed char SplatCsts[] = {
5563 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5564 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5567 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5568 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5569 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
5570 int i = SplatCsts[idx];
5572 // Figure out what shift amount will be used by altivec if shifted by i in
5574 unsigned TypeShiftAmt = i & (SplatBitSize-1);
5576 // vsplti + shl self.
5577 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5578 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5579 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5580 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5581 Intrinsic::ppc_altivec_vslw
5583 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5584 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5587 // vsplti + srl self.
5588 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5589 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5590 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5591 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5592 Intrinsic::ppc_altivec_vsrw
5594 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5595 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5598 // vsplti + sra self.
5599 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5600 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5601 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5602 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5603 Intrinsic::ppc_altivec_vsraw
5605 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5606 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5609 // vsplti + rol self.
5610 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5611 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5612 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5613 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5614 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5615 Intrinsic::ppc_altivec_vrlw
5617 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5618 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5621 // t = vsplti c, result = vsldoi t, t, 1
5622 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5623 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5624 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5626 // t = vsplti c, result = vsldoi t, t, 2
5627 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5628 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5629 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5631 // t = vsplti c, result = vsldoi t, t, 3
5632 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5633 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5634 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5641 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5642 /// the specified operations to build the shuffle.
5643 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5644 SDValue RHS, SelectionDAG &DAG,
5646 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5647 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5648 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5651 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5663 if (OpNum == OP_COPY) {
5664 if (LHSID == (1*9+2)*9+3) return LHS;
5665 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5669 SDValue OpLHS, OpRHS;
5670 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5671 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5675 default: llvm_unreachable("Unknown i32 permute!");
5677 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
5678 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5679 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
5680 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5683 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5684 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5685 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5686 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5689 for (unsigned i = 0; i != 16; ++i)
5690 ShufIdxs[i] = (i&3)+0;
5693 for (unsigned i = 0; i != 16; ++i)
5694 ShufIdxs[i] = (i&3)+4;
5697 for (unsigned i = 0; i != 16; ++i)
5698 ShufIdxs[i] = (i&3)+8;
5701 for (unsigned i = 0; i != 16; ++i)
5702 ShufIdxs[i] = (i&3)+12;
5705 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5707 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5709 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5711 EVT VT = OpLHS.getValueType();
5712 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5713 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5714 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5715 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5718 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
5719 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
5720 /// return the code it can be lowered into. Worst case, it can always be
5721 /// lowered into a vperm.
5722 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5723 SelectionDAG &DAG) const {
5725 SDValue V1 = Op.getOperand(0);
5726 SDValue V2 = Op.getOperand(1);
5727 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5728 EVT VT = Op.getValueType();
5730 // Cases that are handled by instructions that take permute immediates
5731 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5732 // selected by the instruction selector.
5733 if (V2.getOpcode() == ISD::UNDEF) {
5734 if (PPC::isSplatShuffleMask(SVOp, 1) ||
5735 PPC::isSplatShuffleMask(SVOp, 2) ||
5736 PPC::isSplatShuffleMask(SVOp, 4) ||
5737 PPC::isVPKUWUMShuffleMask(SVOp, true) ||
5738 PPC::isVPKUHUMShuffleMask(SVOp, true) ||
5739 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
5740 PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
5741 PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
5742 PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
5743 PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
5744 PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
5745 PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
5750 // Altivec has a variety of "shuffle immediates" that take two vector inputs
5751 // and produce a fixed permutation. If any of these match, do not lower to
5753 if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
5754 PPC::isVPKUHUMShuffleMask(SVOp, false) ||
5755 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
5756 PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
5757 PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
5758 PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
5759 PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
5760 PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
5761 PPC::isVMRGHShuffleMask(SVOp, 4, false))
5764 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
5765 // perfect shuffle table to emit an optimal matching sequence.
5766 ArrayRef<int> PermMask = SVOp->getMask();
5768 unsigned PFIndexes[4];
5769 bool isFourElementShuffle = true;
5770 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5771 unsigned EltNo = 8; // Start out undef.
5772 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
5773 if (PermMask[i*4+j] < 0)
5774 continue; // Undef, ignore it.
5776 unsigned ByteSource = PermMask[i*4+j];
5777 if ((ByteSource & 3) != j) {
5778 isFourElementShuffle = false;
5783 EltNo = ByteSource/4;
5784 } else if (EltNo != ByteSource/4) {
5785 isFourElementShuffle = false;
5789 PFIndexes[i] = EltNo;
5792 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5793 // perfect shuffle vector to determine if it is cost effective to do this as
5794 // discrete instructions, or whether we should use a vperm.
5795 if (isFourElementShuffle) {
5796 // Compute the index in the perfect shuffle table.
5797 unsigned PFTableIndex =
5798 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5800 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5801 unsigned Cost = (PFEntry >> 30);
5803 // Determining when to avoid vperm is tricky. Many things affect the cost
5804 // of vperm, particularly how many times the perm mask needs to be computed.
5805 // For example, if the perm mask can be hoisted out of a loop or is already
5806 // used (perhaps because there are multiple permutes with the same shuffle
5807 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
5808 // the loop requires an extra register.
5810 // As a compromise, we only emit discrete instructions if the shuffle can be
5811 // generated in 3 or fewer operations. When we have loop information
5812 // available, if this block is within a loop, we should avoid using vperm
5813 // for 3-operation perms and use a constant pool load instead.
5815 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5818 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5819 // vector that will get spilled to the constant pool.
5820 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5822 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
5823 // that it is in input element units, not in bytes. Convert now.
5824 EVT EltVT = V1.getValueType().getVectorElementType();
5825 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
5827 SmallVector<SDValue, 16> ResultMask;
5828 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5829 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
5831 for (unsigned j = 0; j != BytesPerElement; ++j)
5832 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
5836 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
5838 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
5841 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
5842 /// altivec comparison. If it is, return true and fill in Opc/isDot with
5843 /// information about the intrinsic.
5844 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
5846 unsigned IntrinsicID =
5847 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
5850 switch (IntrinsicID) {
5851 default: return false;
5852 // Comparison predicates.
5853 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
5854 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
5855 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
5856 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
5857 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
5858 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
5859 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
5860 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
5861 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
5862 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
5863 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
5864 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
5865 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
5867 // Normal Comparisons.
5868 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
5869 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
5870 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
5871 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
5872 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
5873 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
5874 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
5875 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
5876 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
5877 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
5878 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
5879 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
5880 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
5885 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
5886 /// lower, do it, otherwise return null.
5887 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5888 SelectionDAG &DAG) const {
5889 // If this is a lowered altivec predicate compare, CompareOpc is set to the
5890 // opcode number of the comparison.
5894 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
5895 return SDValue(); // Don't custom lower most intrinsics.
5897 // If this is a non-dot comparison, make the VCMP node and we are done.
5899 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
5900 Op.getOperand(1), Op.getOperand(2),
5901 DAG.getConstant(CompareOpc, MVT::i32));
5902 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
5905 // Create the PPCISD altivec 'dot' comparison node.
5907 Op.getOperand(2), // LHS
5908 Op.getOperand(3), // RHS
5909 DAG.getConstant(CompareOpc, MVT::i32)
5911 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
5912 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
5914 // Now that we have the comparison, emit a copy from the CR to a GPR.
5915 // This is flagged to the above dot comparison.
5916 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
5917 DAG.getRegister(PPC::CR6, MVT::i32),
5918 CompNode.getValue(1));
5920 // Unpack the result based on how the target uses it.
5921 unsigned BitNo; // Bit # of CR6.
5922 bool InvertBit; // Invert result?
5923 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
5924 default: // Can't happen, don't crash on invalid number though.
5925 case 0: // Return the value of the EQ bit of CR6.
5926 BitNo = 0; InvertBit = false;
5928 case 1: // Return the inverted value of the EQ bit of CR6.
5929 BitNo = 0; InvertBit = true;
5931 case 2: // Return the value of the LT bit of CR6.
5932 BitNo = 2; InvertBit = false;
5934 case 3: // Return the inverted value of the LT bit of CR6.
5935 BitNo = 2; InvertBit = true;
5939 // Shift the bit into the low position.
5940 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
5941 DAG.getConstant(8-(3-BitNo), MVT::i32));
5943 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
5944 DAG.getConstant(1, MVT::i32));
5946 // If we are supposed to, toggle the bit.
5948 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
5949 DAG.getConstant(1, MVT::i32));
5953 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
5954 SelectionDAG &DAG) const {
5956 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
5957 // instructions), but for smaller types, we need to first extend up to v2i32
5958 // before doing going farther.
5959 if (Op.getValueType() == MVT::v2i64) {
5960 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
5961 if (ExtVT != MVT::v2i32) {
5962 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
5963 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
5964 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
5965 ExtVT.getVectorElementType(), 4)));
5966 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
5967 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
5968 DAG.getValueType(MVT::v2i32));
5977 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
5978 SelectionDAG &DAG) const {
5980 // Create a stack slot that is 16-byte aligned.
5981 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5982 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
5983 EVT PtrVT = getPointerTy();
5984 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5986 // Store the input value into Value#0 of the stack slot.
5987 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
5988 Op.getOperand(0), FIdx, MachinePointerInfo(),
5991 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
5992 false, false, false, 0);
5995 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
5997 if (Op.getValueType() == MVT::v4i32) {
5998 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6000 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
6001 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
6003 SDValue RHSSwap = // = vrlw RHS, 16
6004 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6006 // Shrinkify inputs to v8i16.
6007 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6008 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6009 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6011 // Low parts multiplied together, generating 32-bit results (we ignore the
6013 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6014 LHS, RHS, DAG, dl, MVT::v4i32);
6016 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6017 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6018 // Shift the high parts up 16 bits.
6019 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6021 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6022 } else if (Op.getValueType() == MVT::v8i16) {
6023 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6025 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6027 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6028 LHS, RHS, Zero, DAG, dl);
6029 } else if (Op.getValueType() == MVT::v16i8) {
6030 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6032 // Multiply the even 8-bit parts, producing 16-bit sums.
6033 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6034 LHS, RHS, DAG, dl, MVT::v8i16);
6035 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6037 // Multiply the odd 8-bit parts, producing 16-bit sums.
6038 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6039 LHS, RHS, DAG, dl, MVT::v8i16);
6040 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6042 // Merge the results together.
6044 for (unsigned i = 0; i != 8; ++i) {
6046 Ops[i*2+1] = 2*i+1+16;
6048 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6050 llvm_unreachable("Unknown mul to lower!");
6054 /// LowerOperation - Provide custom lowering hooks for some operations.
6056 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6057 switch (Op.getOpcode()) {
6058 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6059 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6060 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6061 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6062 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6063 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6064 case ISD::SETCC: return LowerSETCC(Op, DAG);
6065 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
6066 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
6068 return LowerVASTART(Op, DAG, PPCSubTarget);
6071 return LowerVAARG(Op, DAG, PPCSubTarget);
6074 return LowerVACOPY(Op, DAG, PPCSubTarget);
6076 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
6077 case ISD::DYNAMIC_STACKALLOC:
6078 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
6080 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
6081 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
6083 case ISD::LOAD: return LowerLOAD(Op, DAG);
6084 case ISD::STORE: return LowerSTORE(Op, DAG);
6085 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
6086 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6087 case ISD::FP_TO_UINT:
6088 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
6090 case ISD::UINT_TO_FP:
6091 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6092 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6094 // Lower 64-bit shifts.
6095 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
6096 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
6097 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
6099 // Vector-related lowering.
6100 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6101 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6102 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6103 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6104 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
6105 case ISD::MUL: return LowerMUL(Op, DAG);
6107 // For counter-based loop handling.
6108 case ISD::INTRINSIC_W_CHAIN: return SDValue();
6110 // Frame & Return address.
6111 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6112 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6116 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6117 SmallVectorImpl<SDValue>&Results,
6118 SelectionDAG &DAG) const {
6119 const TargetMachine &TM = getTargetMachine();
6121 switch (N->getOpcode()) {
6123 llvm_unreachable("Do not know how to custom type legalize this operation!");
6124 case ISD::INTRINSIC_W_CHAIN: {
6125 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6126 Intrinsic::ppc_is_decremented_ctr_nonzero)
6129 assert(N->getValueType(0) == MVT::i1 &&
6130 "Unexpected result type for CTR decrement intrinsic");
6131 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6132 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6133 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6136 Results.push_back(NewInt);
6137 Results.push_back(NewInt.getValue(1));
6141 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
6142 || TM.getSubtarget<PPCSubtarget>().isPPC64())
6145 EVT VT = N->getValueType(0);
6147 if (VT == MVT::i64) {
6148 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
6150 Results.push_back(NewNode);
6151 Results.push_back(NewNode.getValue(1));
6155 case ISD::FP_ROUND_INREG: {
6156 assert(N->getValueType(0) == MVT::ppcf128);
6157 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6158 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6159 MVT::f64, N->getOperand(0),
6160 DAG.getIntPtrConstant(0));
6161 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6162 MVT::f64, N->getOperand(0),
6163 DAG.getIntPtrConstant(1));
6165 // Add the two halves of the long double in round-to-zero mode.
6166 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6168 // We know the low half is about to be thrown away, so just use something
6170 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6174 case ISD::FP_TO_SINT:
6175 // LowerFP_TO_INT() can only handle f32 and f64.
6176 if (N->getOperand(0).getValueType() == MVT::ppcf128)
6178 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6184 //===----------------------------------------------------------------------===//
6185 // Other Lowering Code
6186 //===----------------------------------------------------------------------===//
6189 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6190 bool is64bit, unsigned BinOpcode) const {
6191 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6192 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6194 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6195 MachineFunction *F = BB->getParent();
6196 MachineFunction::iterator It = BB;
6199 unsigned dest = MI->getOperand(0).getReg();
6200 unsigned ptrA = MI->getOperand(1).getReg();
6201 unsigned ptrB = MI->getOperand(2).getReg();
6202 unsigned incr = MI->getOperand(3).getReg();
6203 DebugLoc dl = MI->getDebugLoc();
6205 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6206 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6207 F->insert(It, loopMBB);
6208 F->insert(It, exitMBB);
6209 exitMBB->splice(exitMBB->begin(), BB,
6210 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6211 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6213 MachineRegisterInfo &RegInfo = F->getRegInfo();
6214 unsigned TmpReg = (!BinOpcode) ? incr :
6215 RegInfo.createVirtualRegister(
6216 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6217 (const TargetRegisterClass *) &PPC::GPRCRegClass);
6221 // fallthrough --> loopMBB
6222 BB->addSuccessor(loopMBB);
6225 // l[wd]arx dest, ptr
6226 // add r0, dest, incr
6227 // st[wd]cx. r0, ptr
6229 // fallthrough --> exitMBB
6231 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6232 .addReg(ptrA).addReg(ptrB);
6234 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6235 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6236 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6237 BuildMI(BB, dl, TII->get(PPC::BCC))
6238 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6239 BB->addSuccessor(loopMBB);
6240 BB->addSuccessor(exitMBB);
6249 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6250 MachineBasicBlock *BB,
6251 bool is8bit, // operation
6252 unsigned BinOpcode) const {
6253 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6254 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6255 // In 64 bit mode we have to use 64 bits for addresses, even though the
6256 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
6257 // registers without caring whether they're 32 or 64, but here we're
6258 // doing actual arithmetic on the addresses.
6259 bool is64bit = PPCSubTarget.isPPC64();
6260 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6262 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6263 MachineFunction *F = BB->getParent();
6264 MachineFunction::iterator It = BB;
6267 unsigned dest = MI->getOperand(0).getReg();
6268 unsigned ptrA = MI->getOperand(1).getReg();
6269 unsigned ptrB = MI->getOperand(2).getReg();
6270 unsigned incr = MI->getOperand(3).getReg();
6271 DebugLoc dl = MI->getDebugLoc();
6273 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6274 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6275 F->insert(It, loopMBB);
6276 F->insert(It, exitMBB);
6277 exitMBB->splice(exitMBB->begin(), BB,
6278 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6279 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6281 MachineRegisterInfo &RegInfo = F->getRegInfo();
6282 const TargetRegisterClass *RC =
6283 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6284 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6285 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6286 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6287 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6288 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6289 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6290 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6291 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6292 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6293 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6294 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6295 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6297 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6301 // fallthrough --> loopMBB
6302 BB->addSuccessor(loopMBB);
6304 // The 4-byte load must be aligned, while a char or short may be
6305 // anywhere in the word. Hence all this nasty bookkeeping code.
6306 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6307 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6308 // xori shift, shift1, 24 [16]
6309 // rlwinm ptr, ptr1, 0, 0, 29
6310 // slw incr2, incr, shift
6311 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6312 // slw mask, mask2, shift
6314 // lwarx tmpDest, ptr
6315 // add tmp, tmpDest, incr2
6316 // andc tmp2, tmpDest, mask
6317 // and tmp3, tmp, mask
6318 // or tmp4, tmp3, tmp2
6321 // fallthrough --> exitMBB
6322 // srw dest, tmpDest, shift
6323 if (ptrA != ZeroReg) {
6324 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6325 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6326 .addReg(ptrA).addReg(ptrB);
6330 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6331 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6332 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6333 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6335 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6336 .addReg(Ptr1Reg).addImm(0).addImm(61);
6338 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6339 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6340 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6341 .addReg(incr).addReg(ShiftReg);
6343 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6345 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6346 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6348 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6349 .addReg(Mask2Reg).addReg(ShiftReg);
6352 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6353 .addReg(ZeroReg).addReg(PtrReg);
6355 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6356 .addReg(Incr2Reg).addReg(TmpDestReg);
6357 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6358 .addReg(TmpDestReg).addReg(MaskReg);
6359 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6360 .addReg(TmpReg).addReg(MaskReg);
6361 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6362 .addReg(Tmp3Reg).addReg(Tmp2Reg);
6363 BuildMI(BB, dl, TII->get(PPC::STWCX))
6364 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6365 BuildMI(BB, dl, TII->get(PPC::BCC))
6366 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6367 BB->addSuccessor(loopMBB);
6368 BB->addSuccessor(exitMBB);
6373 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6378 llvm::MachineBasicBlock*
6379 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6380 MachineBasicBlock *MBB) const {
6381 DebugLoc DL = MI->getDebugLoc();
6382 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6384 MachineFunction *MF = MBB->getParent();
6385 MachineRegisterInfo &MRI = MF->getRegInfo();
6387 const BasicBlock *BB = MBB->getBasicBlock();
6388 MachineFunction::iterator I = MBB;
6392 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6393 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6395 unsigned DstReg = MI->getOperand(0).getReg();
6396 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6397 assert(RC->hasType(MVT::i32) && "Invalid destination!");
6398 unsigned mainDstReg = MRI.createVirtualRegister(RC);
6399 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6401 MVT PVT = getPointerTy();
6402 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6403 "Invalid Pointer Size!");
6404 // For v = setjmp(buf), we generate
6407 // SjLjSetup mainMBB
6413 // buf[LabelOffset] = LR
6417 // v = phi(main, restore)
6420 MachineBasicBlock *thisMBB = MBB;
6421 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6422 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6423 MF->insert(I, mainMBB);
6424 MF->insert(I, sinkMBB);
6426 MachineInstrBuilder MIB;
6428 // Transfer the remainder of BB and its successor edges to sinkMBB.
6429 sinkMBB->splice(sinkMBB->begin(), MBB,
6430 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6431 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6433 // Note that the structure of the jmp_buf used here is not compatible
6434 // with that used by libc, and is not designed to be. Specifically, it
6435 // stores only those 'reserved' registers that LLVM does not otherwise
6436 // understand how to spill. Also, by convention, by the time this
6437 // intrinsic is called, Clang has already stored the frame address in the
6438 // first slot of the buffer and stack address in the third. Following the
6439 // X86 target code, we'll store the jump address in the second slot. We also
6440 // need to save the TOC pointer (R2) to handle jumps between shared
6441 // libraries, and that will be stored in the fourth slot. The thread
6442 // identifier (R13) is not affected.
6445 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6446 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6447 const int64_t BPOffset = 4 * PVT.getStoreSize();
6449 // Prepare IP either in reg.
6450 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6451 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6452 unsigned BufReg = MI->getOperand(1).getReg();
6454 if (PPCSubTarget.isPPC64() && PPCSubTarget.isSVR4ABI()) {
6455 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6459 MIB.setMemRefs(MMOBegin, MMOEnd);
6462 // Naked functions never have a base pointer, and so we use r1. For all
6463 // other functions, this decision must be delayed until during PEI.
6465 if (MF->getFunction()->getAttributes().hasAttribute(
6466 AttributeSet::FunctionIndex, Attribute::Naked))
6467 BaseReg = PPCSubTarget.isPPC64() ? PPC::X1 : PPC::R1;
6469 BaseReg = PPCSubTarget.isPPC64() ? PPC::BP8 : PPC::BP;
6471 MIB = BuildMI(*thisMBB, MI, DL,
6472 TII->get(PPCSubTarget.isPPC64() ? PPC::STD : PPC::STW))
6476 MIB.setMemRefs(MMOBegin, MMOEnd);
6479 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6480 const PPCRegisterInfo *TRI =
6481 static_cast<const PPCRegisterInfo*>(getTargetMachine().getRegisterInfo());
6482 MIB.addRegMask(TRI->getNoPreservedMask());
6484 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6486 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6488 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6490 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6491 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6495 MIB = BuildMI(mainMBB, DL,
6496 TII->get(PPCSubTarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6499 if (PPCSubTarget.isPPC64()) {
6500 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6502 .addImm(LabelOffset)
6505 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6507 .addImm(LabelOffset)
6511 MIB.setMemRefs(MMOBegin, MMOEnd);
6513 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6514 mainMBB->addSuccessor(sinkMBB);
6517 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6518 TII->get(PPC::PHI), DstReg)
6519 .addReg(mainDstReg).addMBB(mainMBB)
6520 .addReg(restoreDstReg).addMBB(thisMBB);
6522 MI->eraseFromParent();
6527 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6528 MachineBasicBlock *MBB) const {
6529 DebugLoc DL = MI->getDebugLoc();
6530 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6532 MachineFunction *MF = MBB->getParent();
6533 MachineRegisterInfo &MRI = MF->getRegInfo();
6536 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6537 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6539 MVT PVT = getPointerTy();
6540 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6541 "Invalid Pointer Size!");
6543 const TargetRegisterClass *RC =
6544 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6545 unsigned Tmp = MRI.createVirtualRegister(RC);
6546 // Since FP is only updated here but NOT referenced, it's treated as GPR.
6547 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6548 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6549 unsigned BP = (PVT == MVT::i64) ? PPC::X30 : PPC::R30;
6551 MachineInstrBuilder MIB;
6553 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6554 const int64_t SPOffset = 2 * PVT.getStoreSize();
6555 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6556 const int64_t BPOffset = 4 * PVT.getStoreSize();
6558 unsigned BufReg = MI->getOperand(0).getReg();
6560 // Reload FP (the jumped-to function may not have had a
6561 // frame pointer, and if so, then its r31 will be restored
6563 if (PVT == MVT::i64) {
6564 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6568 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6572 MIB.setMemRefs(MMOBegin, MMOEnd);
6575 if (PVT == MVT::i64) {
6576 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6577 .addImm(LabelOffset)
6580 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6581 .addImm(LabelOffset)
6584 MIB.setMemRefs(MMOBegin, MMOEnd);
6587 if (PVT == MVT::i64) {
6588 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6592 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6596 MIB.setMemRefs(MMOBegin, MMOEnd);
6599 if (PVT == MVT::i64) {
6600 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
6604 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
6608 MIB.setMemRefs(MMOBegin, MMOEnd);
6611 if (PVT == MVT::i64 && PPCSubTarget.isSVR4ABI()) {
6612 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6616 MIB.setMemRefs(MMOBegin, MMOEnd);
6620 BuildMI(*MBB, MI, DL,
6621 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6622 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6624 MI->eraseFromParent();
6629 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6630 MachineBasicBlock *BB) const {
6631 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6632 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6633 return emitEHSjLjSetJmp(MI, BB);
6634 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6635 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6636 return emitEHSjLjLongJmp(MI, BB);
6639 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6641 // To "insert" these instructions we actually have to insert their
6642 // control-flow patterns.
6643 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6644 MachineFunction::iterator It = BB;
6647 MachineFunction *F = BB->getParent();
6649 if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6650 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6651 MI->getOpcode() == PPC::SELECT_I4 ||
6652 MI->getOpcode() == PPC::SELECT_I8)) {
6653 SmallVector<MachineOperand, 2> Cond;
6654 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6655 MI->getOpcode() == PPC::SELECT_CC_I8)
6656 Cond.push_back(MI->getOperand(4));
6658 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
6659 Cond.push_back(MI->getOperand(1));
6661 DebugLoc dl = MI->getDebugLoc();
6662 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6663 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
6664 Cond, MI->getOperand(2).getReg(),
6665 MI->getOperand(3).getReg());
6666 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6667 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6668 MI->getOpcode() == PPC::SELECT_CC_F4 ||
6669 MI->getOpcode() == PPC::SELECT_CC_F8 ||
6670 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
6671 MI->getOpcode() == PPC::SELECT_I4 ||
6672 MI->getOpcode() == PPC::SELECT_I8 ||
6673 MI->getOpcode() == PPC::SELECT_F4 ||
6674 MI->getOpcode() == PPC::SELECT_F8 ||
6675 MI->getOpcode() == PPC::SELECT_VRRC) {
6676 // The incoming instruction knows the destination vreg to set, the
6677 // condition code register to branch on, the true/false values to
6678 // select between, and a branch opcode to use.
6683 // cmpTY ccX, r1, r2
6685 // fallthrough --> copy0MBB
6686 MachineBasicBlock *thisMBB = BB;
6687 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6688 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6689 DebugLoc dl = MI->getDebugLoc();
6690 F->insert(It, copy0MBB);
6691 F->insert(It, sinkMBB);
6693 // Transfer the remainder of BB and its successor edges to sinkMBB.
6694 sinkMBB->splice(sinkMBB->begin(), BB,
6695 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6696 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6698 // Next, add the true and fallthrough blocks as its successors.
6699 BB->addSuccessor(copy0MBB);
6700 BB->addSuccessor(sinkMBB);
6702 if (MI->getOpcode() == PPC::SELECT_I4 ||
6703 MI->getOpcode() == PPC::SELECT_I8 ||
6704 MI->getOpcode() == PPC::SELECT_F4 ||
6705 MI->getOpcode() == PPC::SELECT_F8 ||
6706 MI->getOpcode() == PPC::SELECT_VRRC) {
6707 BuildMI(BB, dl, TII->get(PPC::BC))
6708 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6710 unsigned SelectPred = MI->getOperand(4).getImm();
6711 BuildMI(BB, dl, TII->get(PPC::BCC))
6712 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6716 // %FalseValue = ...
6717 // # fallthrough to sinkMBB
6720 // Update machine-CFG edges
6721 BB->addSuccessor(sinkMBB);
6724 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6727 BuildMI(*BB, BB->begin(), dl,
6728 TII->get(PPC::PHI), MI->getOperand(0).getReg())
6729 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
6730 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6732 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
6733 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
6734 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
6735 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
6736 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
6737 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
6738 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
6739 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
6741 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
6742 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
6743 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
6744 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
6745 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
6746 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
6747 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
6748 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
6750 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
6751 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
6752 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
6753 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
6754 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
6755 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
6756 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
6757 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
6759 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
6760 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
6761 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
6762 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
6763 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
6764 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
6765 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
6766 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
6768 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
6769 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
6770 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
6771 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
6772 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
6773 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
6774 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
6775 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
6777 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
6778 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
6779 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
6780 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
6781 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
6782 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
6783 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
6784 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
6786 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
6787 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
6788 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
6789 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
6790 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
6791 BB = EmitAtomicBinary(MI, BB, false, 0);
6792 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
6793 BB = EmitAtomicBinary(MI, BB, true, 0);
6795 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
6796 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
6797 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
6799 unsigned dest = MI->getOperand(0).getReg();
6800 unsigned ptrA = MI->getOperand(1).getReg();
6801 unsigned ptrB = MI->getOperand(2).getReg();
6802 unsigned oldval = MI->getOperand(3).getReg();
6803 unsigned newval = MI->getOperand(4).getReg();
6804 DebugLoc dl = MI->getDebugLoc();
6806 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6807 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6808 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6809 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6810 F->insert(It, loop1MBB);
6811 F->insert(It, loop2MBB);
6812 F->insert(It, midMBB);
6813 F->insert(It, exitMBB);
6814 exitMBB->splice(exitMBB->begin(), BB,
6815 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6816 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6820 // fallthrough --> loopMBB
6821 BB->addSuccessor(loop1MBB);
6824 // l[wd]arx dest, ptr
6825 // cmp[wd] dest, oldval
6828 // st[wd]cx. newval, ptr
6832 // st[wd]cx. dest, ptr
6835 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6836 .addReg(ptrA).addReg(ptrB);
6837 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
6838 .addReg(oldval).addReg(dest);
6839 BuildMI(BB, dl, TII->get(PPC::BCC))
6840 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6841 BB->addSuccessor(loop2MBB);
6842 BB->addSuccessor(midMBB);
6845 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6846 .addReg(newval).addReg(ptrA).addReg(ptrB);
6847 BuildMI(BB, dl, TII->get(PPC::BCC))
6848 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6849 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6850 BB->addSuccessor(loop1MBB);
6851 BB->addSuccessor(exitMBB);
6854 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6855 .addReg(dest).addReg(ptrA).addReg(ptrB);
6856 BB->addSuccessor(exitMBB);
6861 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
6862 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
6863 // We must use 64-bit registers for addresses when targeting 64-bit,
6864 // since we're actually doing arithmetic on them. Other registers
6866 bool is64bit = PPCSubTarget.isPPC64();
6867 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
6869 unsigned dest = MI->getOperand(0).getReg();
6870 unsigned ptrA = MI->getOperand(1).getReg();
6871 unsigned ptrB = MI->getOperand(2).getReg();
6872 unsigned oldval = MI->getOperand(3).getReg();
6873 unsigned newval = MI->getOperand(4).getReg();
6874 DebugLoc dl = MI->getDebugLoc();
6876 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6877 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6878 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6879 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6880 F->insert(It, loop1MBB);
6881 F->insert(It, loop2MBB);
6882 F->insert(It, midMBB);
6883 F->insert(It, exitMBB);
6884 exitMBB->splice(exitMBB->begin(), BB,
6885 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6886 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6888 MachineRegisterInfo &RegInfo = F->getRegInfo();
6889 const TargetRegisterClass *RC =
6890 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6891 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6892 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6893 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6894 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6895 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
6896 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
6897 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
6898 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
6899 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6900 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6901 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6902 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6903 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6904 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6906 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
6907 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6910 // fallthrough --> loopMBB
6911 BB->addSuccessor(loop1MBB);
6913 // The 4-byte load must be aligned, while a char or short may be
6914 // anywhere in the word. Hence all this nasty bookkeeping code.
6915 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6916 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6917 // xori shift, shift1, 24 [16]
6918 // rlwinm ptr, ptr1, 0, 0, 29
6919 // slw newval2, newval, shift
6920 // slw oldval2, oldval,shift
6921 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6922 // slw mask, mask2, shift
6923 // and newval3, newval2, mask
6924 // and oldval3, oldval2, mask
6926 // lwarx tmpDest, ptr
6927 // and tmp, tmpDest, mask
6928 // cmpw tmp, oldval3
6931 // andc tmp2, tmpDest, mask
6932 // or tmp4, tmp2, newval3
6937 // stwcx. tmpDest, ptr
6939 // srw dest, tmpDest, shift
6940 if (ptrA != ZeroReg) {
6941 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6942 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6943 .addReg(ptrA).addReg(ptrB);
6947 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6948 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6949 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6950 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6952 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6953 .addReg(Ptr1Reg).addImm(0).addImm(61);
6955 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6956 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6957 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
6958 .addReg(newval).addReg(ShiftReg);
6959 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
6960 .addReg(oldval).addReg(ShiftReg);
6962 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6964 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6965 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
6966 .addReg(Mask3Reg).addImm(65535);
6968 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6969 .addReg(Mask2Reg).addReg(ShiftReg);
6970 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
6971 .addReg(NewVal2Reg).addReg(MaskReg);
6972 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
6973 .addReg(OldVal2Reg).addReg(MaskReg);
6976 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6977 .addReg(ZeroReg).addReg(PtrReg);
6978 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
6979 .addReg(TmpDestReg).addReg(MaskReg);
6980 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
6981 .addReg(TmpReg).addReg(OldVal3Reg);
6982 BuildMI(BB, dl, TII->get(PPC::BCC))
6983 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6984 BB->addSuccessor(loop2MBB);
6985 BB->addSuccessor(midMBB);
6988 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
6989 .addReg(TmpDestReg).addReg(MaskReg);
6990 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
6991 .addReg(Tmp2Reg).addReg(NewVal3Reg);
6992 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
6993 .addReg(ZeroReg).addReg(PtrReg);
6994 BuildMI(BB, dl, TII->get(PPC::BCC))
6995 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6996 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6997 BB->addSuccessor(loop1MBB);
6998 BB->addSuccessor(exitMBB);
7001 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
7002 .addReg(ZeroReg).addReg(PtrReg);
7003 BB->addSuccessor(exitMBB);
7008 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7010 } else if (MI->getOpcode() == PPC::FADDrtz) {
7011 // This pseudo performs an FADD with rounding mode temporarily forced
7012 // to round-to-zero. We emit this via custom inserter since the FPSCR
7013 // is not modeled at the SelectionDAG level.
7014 unsigned Dest = MI->getOperand(0).getReg();
7015 unsigned Src1 = MI->getOperand(1).getReg();
7016 unsigned Src2 = MI->getOperand(2).getReg();
7017 DebugLoc dl = MI->getDebugLoc();
7019 MachineRegisterInfo &RegInfo = F->getRegInfo();
7020 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7022 // Save FPSCR value.
7023 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7025 // Set rounding mode to round-to-zero.
7026 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7027 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7029 // Perform addition.
7030 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7032 // Restore FPSCR value.
7033 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
7034 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7035 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7036 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7037 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7038 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7039 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7040 PPC::ANDIo8 : PPC::ANDIo;
7041 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7042 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7044 MachineRegisterInfo &RegInfo = F->getRegInfo();
7045 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7046 &PPC::GPRCRegClass :
7047 &PPC::G8RCRegClass);
7049 DebugLoc dl = MI->getDebugLoc();
7050 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7051 .addReg(MI->getOperand(1).getReg()).addImm(1);
7052 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7053 MI->getOperand(0).getReg())
7054 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7056 llvm_unreachable("Unexpected instr type to insert");
7059 MI->eraseFromParent(); // The pseudo instruction is gone now.
7063 //===----------------------------------------------------------------------===//
7064 // Target Optimization Hooks
7065 //===----------------------------------------------------------------------===//
7067 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op,
7068 DAGCombinerInfo &DCI) const {
7069 if (DCI.isAfterLegalizeVectorOps())
7072 EVT VT = Op.getValueType();
7074 if ((VT == MVT::f32 && PPCSubTarget.hasFRES()) ||
7075 (VT == MVT::f64 && PPCSubTarget.hasFRE()) ||
7076 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec()) ||
7077 (VT == MVT::v2f64 && PPCSubTarget.hasVSX())) {
7079 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7080 // For the reciprocal, we need to find the zero of the function:
7081 // F(X) = A X - 1 [which has a zero at X = 1/A]
7083 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
7084 // does not require additional intermediate precision]
7086 // Convergence is quadratic, so we essentially double the number of digits
7087 // correct after every iteration. The minimum architected relative
7088 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7089 // 23 digits and double has 52 digits.
7090 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
7091 if (VT.getScalarType() == MVT::f64)
7094 SelectionDAG &DAG = DCI.DAG;
7098 DAG.getConstantFP(1.0, VT.getScalarType());
7099 if (VT.isVector()) {
7100 assert(VT.getVectorNumElements() == 4 &&
7101 "Unknown vector type");
7102 FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7103 FPOne, FPOne, FPOne, FPOne);
7106 SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op);
7107 DCI.AddToWorklist(Est.getNode());
7109 // Newton iterations: Est = Est + Est (1 - Arg * Est)
7110 for (int i = 0; i < Iterations; ++i) {
7111 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est);
7112 DCI.AddToWorklist(NewEst.getNode());
7114 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst);
7115 DCI.AddToWorklist(NewEst.getNode());
7117 NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7118 DCI.AddToWorklist(NewEst.getNode());
7120 Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst);
7121 DCI.AddToWorklist(Est.getNode());
7130 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op,
7131 DAGCombinerInfo &DCI) const {
7132 if (DCI.isAfterLegalizeVectorOps())
7135 EVT VT = Op.getValueType();
7137 if ((VT == MVT::f32 && PPCSubTarget.hasFRSQRTES()) ||
7138 (VT == MVT::f64 && PPCSubTarget.hasFRSQRTE()) ||
7139 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec()) ||
7140 (VT == MVT::v2f64 && PPCSubTarget.hasVSX())) {
7142 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7143 // For the reciprocal sqrt, we need to find the zero of the function:
7144 // F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
7146 // X_{i+1} = X_i (1.5 - A X_i^2 / 2)
7147 // As a result, we precompute A/2 prior to the iteration loop.
7149 // Convergence is quadratic, so we essentially double the number of digits
7150 // correct after every iteration. The minimum architected relative
7151 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7152 // 23 digits and double has 52 digits.
7153 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
7154 if (VT.getScalarType() == MVT::f64)
7157 SelectionDAG &DAG = DCI.DAG;
7160 SDValue FPThreeHalves =
7161 DAG.getConstantFP(1.5, VT.getScalarType());
7162 if (VT.isVector()) {
7163 assert(VT.getVectorNumElements() == 4 &&
7164 "Unknown vector type");
7165 FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7166 FPThreeHalves, FPThreeHalves,
7167 FPThreeHalves, FPThreeHalves);
7170 SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op);
7171 DCI.AddToWorklist(Est.getNode());
7173 // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that
7174 // this entire sequence requires only one FP constant.
7175 SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op);
7176 DCI.AddToWorklist(HalfArg.getNode());
7178 HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op);
7179 DCI.AddToWorklist(HalfArg.getNode());
7181 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
7182 for (int i = 0; i < Iterations; ++i) {
7183 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est);
7184 DCI.AddToWorklist(NewEst.getNode());
7186 NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst);
7187 DCI.AddToWorklist(NewEst.getNode());
7189 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst);
7190 DCI.AddToWorklist(NewEst.getNode());
7192 Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7193 DCI.AddToWorklist(Est.getNode());
7202 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7203 // not enforce equality of the chain operands.
7204 static bool isConsecutiveLS(LSBaseSDNode *LS, LSBaseSDNode *Base,
7205 unsigned Bytes, int Dist,
7206 SelectionDAG &DAG) {
7207 EVT VT = LS->getMemoryVT();
7208 if (VT.getSizeInBits() / 8 != Bytes)
7211 SDValue Loc = LS->getBasePtr();
7212 SDValue BaseLoc = Base->getBasePtr();
7213 if (Loc.getOpcode() == ISD::FrameIndex) {
7214 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7216 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7217 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7218 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7219 int FS = MFI->getObjectSize(FI);
7220 int BFS = MFI->getObjectSize(BFI);
7221 if (FS != BFS || FS != (int)Bytes) return false;
7222 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7226 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7227 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7230 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7231 const GlobalValue *GV1 = nullptr;
7232 const GlobalValue *GV2 = nullptr;
7233 int64_t Offset1 = 0;
7234 int64_t Offset2 = 0;
7235 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7236 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7237 if (isGA1 && isGA2 && GV1 == GV2)
7238 return Offset1 == (Offset2 + Dist*Bytes);
7242 // Return true is there is a nearyby consecutive load to the one provided
7243 // (regardless of alignment). We search up and down the chain, looking though
7244 // token factors and other loads (but nothing else). As a result, a true
7245 // results indicates that it is safe to create a new consecutive load adjacent
7246 // to the load provided.
7247 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7248 SDValue Chain = LD->getChain();
7249 EVT VT = LD->getMemoryVT();
7251 SmallSet<SDNode *, 16> LoadRoots;
7252 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7253 SmallSet<SDNode *, 16> Visited;
7255 // First, search up the chain, branching to follow all token-factor operands.
7256 // If we find a consecutive load, then we're done, otherwise, record all
7257 // nodes just above the top-level loads and token factors.
7258 while (!Queue.empty()) {
7259 SDNode *ChainNext = Queue.pop_back_val();
7260 if (!Visited.insert(ChainNext))
7263 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(ChainNext)) {
7264 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7267 if (!Visited.count(ChainLD->getChain().getNode()))
7268 Queue.push_back(ChainLD->getChain().getNode());
7269 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7270 for (SDNode::op_iterator O = ChainNext->op_begin(),
7271 OE = ChainNext->op_end(); O != OE; ++O)
7272 if (!Visited.count(O->getNode()))
7273 Queue.push_back(O->getNode());
7275 LoadRoots.insert(ChainNext);
7278 // Second, search down the chain, starting from the top-level nodes recorded
7279 // in the first phase. These top-level nodes are the nodes just above all
7280 // loads and token factors. Starting with their uses, recursively look though
7281 // all loads (just the chain uses) and token factors to find a consecutive
7286 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7287 IE = LoadRoots.end(); I != IE; ++I) {
7288 Queue.push_back(*I);
7290 while (!Queue.empty()) {
7291 SDNode *LoadRoot = Queue.pop_back_val();
7292 if (!Visited.insert(LoadRoot))
7295 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(LoadRoot))
7296 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7299 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7300 UE = LoadRoot->use_end(); UI != UE; ++UI)
7301 if (((isa<LoadSDNode>(*UI) &&
7302 cast<LoadSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7303 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7304 Queue.push_back(*UI);
7311 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7312 DAGCombinerInfo &DCI) const {
7313 SelectionDAG &DAG = DCI.DAG;
7316 assert(PPCSubTarget.useCRBits() &&
7317 "Expecting to be tracking CR bits");
7318 // If we're tracking CR bits, we need to be careful that we don't have:
7319 // trunc(binary-ops(zext(x), zext(y)))
7321 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7322 // such that we're unnecessarily moving things into GPRs when it would be
7323 // better to keep them in CR bits.
7325 // Note that trunc here can be an actual i1 trunc, or can be the effective
7326 // truncation that comes from a setcc or select_cc.
7327 if (N->getOpcode() == ISD::TRUNCATE &&
7328 N->getValueType(0) != MVT::i1)
7331 if (N->getOperand(0).getValueType() != MVT::i32 &&
7332 N->getOperand(0).getValueType() != MVT::i64)
7335 if (N->getOpcode() == ISD::SETCC ||
7336 N->getOpcode() == ISD::SELECT_CC) {
7337 // If we're looking at a comparison, then we need to make sure that the
7338 // high bits (all except for the first) don't matter the result.
7340 cast<CondCodeSDNode>(N->getOperand(
7341 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7342 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7344 if (ISD::isSignedIntSetCC(CC)) {
7345 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7346 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7348 } else if (ISD::isUnsignedIntSetCC(CC)) {
7349 if (!DAG.MaskedValueIsZero(N->getOperand(0),
7350 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7351 !DAG.MaskedValueIsZero(N->getOperand(1),
7352 APInt::getHighBitsSet(OpBits, OpBits-1)))
7355 // This is neither a signed nor an unsigned comparison, just make sure
7356 // that the high bits are equal.
7357 APInt Op1Zero, Op1One;
7358 APInt Op2Zero, Op2One;
7359 DAG.ComputeMaskedBits(N->getOperand(0), Op1Zero, Op1One);
7360 DAG.ComputeMaskedBits(N->getOperand(1), Op2Zero, Op2One);
7362 // We don't really care about what is known about the first bit (if
7363 // anything), so clear it in all masks prior to comparing them.
7364 Op1Zero.clearBit(0); Op1One.clearBit(0);
7365 Op2Zero.clearBit(0); Op2One.clearBit(0);
7367 if (Op1Zero != Op2Zero || Op1One != Op2One)
7372 // We now know that the higher-order bits are irrelevant, we just need to
7373 // make sure that all of the intermediate operations are bit operations, and
7374 // all inputs are extensions.
7375 if (N->getOperand(0).getOpcode() != ISD::AND &&
7376 N->getOperand(0).getOpcode() != ISD::OR &&
7377 N->getOperand(0).getOpcode() != ISD::XOR &&
7378 N->getOperand(0).getOpcode() != ISD::SELECT &&
7379 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7380 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7381 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7382 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7383 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7386 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7387 N->getOperand(1).getOpcode() != ISD::AND &&
7388 N->getOperand(1).getOpcode() != ISD::OR &&
7389 N->getOperand(1).getOpcode() != ISD::XOR &&
7390 N->getOperand(1).getOpcode() != ISD::SELECT &&
7391 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7392 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7393 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7394 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7395 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7398 SmallVector<SDValue, 4> Inputs;
7399 SmallVector<SDValue, 8> BinOps, PromOps;
7400 SmallPtrSet<SDNode *, 16> Visited;
7402 for (unsigned i = 0; i < 2; ++i) {
7403 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7404 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7405 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7406 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7407 isa<ConstantSDNode>(N->getOperand(i)))
7408 Inputs.push_back(N->getOperand(i));
7410 BinOps.push_back(N->getOperand(i));
7412 if (N->getOpcode() == ISD::TRUNCATE)
7416 // Visit all inputs, collect all binary operations (and, or, xor and
7417 // select) that are all fed by extensions.
7418 while (!BinOps.empty()) {
7419 SDValue BinOp = BinOps.back();
7422 if (!Visited.insert(BinOp.getNode()))
7425 PromOps.push_back(BinOp);
7427 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7428 // The condition of the select is not promoted.
7429 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7431 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7434 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7435 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7436 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7437 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7438 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7439 Inputs.push_back(BinOp.getOperand(i));
7440 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7441 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7442 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7443 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7444 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
7445 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7446 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7447 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7448 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
7449 BinOps.push_back(BinOp.getOperand(i));
7451 // We have an input that is not an extension or another binary
7452 // operation; we'll abort this transformation.
7458 // Make sure that this is a self-contained cluster of operations (which
7459 // is not quite the same thing as saying that everything has only one
7461 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7462 if (isa<ConstantSDNode>(Inputs[i]))
7465 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7466 UE = Inputs[i].getNode()->use_end();
7469 if (User != N && !Visited.count(User))
7472 // Make sure that we're not going to promote the non-output-value
7473 // operand(s) or SELECT or SELECT_CC.
7474 // FIXME: Although we could sometimes handle this, and it does occur in
7475 // practice that one of the condition inputs to the select is also one of
7476 // the outputs, we currently can't deal with this.
7477 if (User->getOpcode() == ISD::SELECT) {
7478 if (User->getOperand(0) == Inputs[i])
7480 } else if (User->getOpcode() == ISD::SELECT_CC) {
7481 if (User->getOperand(0) == Inputs[i] ||
7482 User->getOperand(1) == Inputs[i])
7488 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7489 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7490 UE = PromOps[i].getNode()->use_end();
7493 if (User != N && !Visited.count(User))
7496 // Make sure that we're not going to promote the non-output-value
7497 // operand(s) or SELECT or SELECT_CC.
7498 // FIXME: Although we could sometimes handle this, and it does occur in
7499 // practice that one of the condition inputs to the select is also one of
7500 // the outputs, we currently can't deal with this.
7501 if (User->getOpcode() == ISD::SELECT) {
7502 if (User->getOperand(0) == PromOps[i])
7504 } else if (User->getOpcode() == ISD::SELECT_CC) {
7505 if (User->getOperand(0) == PromOps[i] ||
7506 User->getOperand(1) == PromOps[i])
7512 // Replace all inputs with the extension operand.
7513 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7514 // Constants may have users outside the cluster of to-be-promoted nodes,
7515 // and so we need to replace those as we do the promotions.
7516 if (isa<ConstantSDNode>(Inputs[i]))
7519 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
7522 // Replace all operations (these are all the same, but have a different
7523 // (i1) return type). DAG.getNode will validate that the types of
7524 // a binary operator match, so go through the list in reverse so that
7525 // we've likely promoted both operands first. Any intermediate truncations or
7526 // extensions disappear.
7527 while (!PromOps.empty()) {
7528 SDValue PromOp = PromOps.back();
7531 if (PromOp.getOpcode() == ISD::TRUNCATE ||
7532 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
7533 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
7534 PromOp.getOpcode() == ISD::ANY_EXTEND) {
7535 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
7536 PromOp.getOperand(0).getValueType() != MVT::i1) {
7537 // The operand is not yet ready (see comment below).
7538 PromOps.insert(PromOps.begin(), PromOp);
7542 SDValue RepValue = PromOp.getOperand(0);
7543 if (isa<ConstantSDNode>(RepValue))
7544 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
7546 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
7551 switch (PromOp.getOpcode()) {
7552 default: C = 0; break;
7553 case ISD::SELECT: C = 1; break;
7554 case ISD::SELECT_CC: C = 2; break;
7557 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7558 PromOp.getOperand(C).getValueType() != MVT::i1) ||
7559 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7560 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
7561 // The to-be-promoted operands of this node have not yet been
7562 // promoted (this should be rare because we're going through the
7563 // list backward, but if one of the operands has several users in
7564 // this cluster of to-be-promoted nodes, it is possible).
7565 PromOps.insert(PromOps.begin(), PromOp);
7569 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7570 PromOp.getNode()->op_end());
7572 // If there are any constant inputs, make sure they're replaced now.
7573 for (unsigned i = 0; i < 2; ++i)
7574 if (isa<ConstantSDNode>(Ops[C+i]))
7575 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
7577 DAG.ReplaceAllUsesOfValueWith(PromOp,
7578 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
7581 // Now we're left with the initial truncation itself.
7582 if (N->getOpcode() == ISD::TRUNCATE)
7583 return N->getOperand(0);
7585 // Otherwise, this is a comparison. The operands to be compared have just
7586 // changed type (to i1), but everything else is the same.
7587 return SDValue(N, 0);
7590 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
7591 DAGCombinerInfo &DCI) const {
7592 SelectionDAG &DAG = DCI.DAG;
7595 // If we're tracking CR bits, we need to be careful that we don't have:
7596 // zext(binary-ops(trunc(x), trunc(y)))
7598 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
7599 // such that we're unnecessarily moving things into CR bits that can more
7600 // efficiently stay in GPRs. Note that if we're not certain that the high
7601 // bits are set as required by the final extension, we still may need to do
7602 // some masking to get the proper behavior.
7604 // This same functionality is important on PPC64 when dealing with
7605 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
7606 // the return values of functions. Because it is so similar, it is handled
7609 if (N->getValueType(0) != MVT::i32 &&
7610 N->getValueType(0) != MVT::i64)
7613 if (!((N->getOperand(0).getValueType() == MVT::i1 &&
7614 PPCSubTarget.useCRBits()) ||
7615 (N->getOperand(0).getValueType() == MVT::i32 &&
7616 PPCSubTarget.isPPC64())))
7619 if (N->getOperand(0).getOpcode() != ISD::AND &&
7620 N->getOperand(0).getOpcode() != ISD::OR &&
7621 N->getOperand(0).getOpcode() != ISD::XOR &&
7622 N->getOperand(0).getOpcode() != ISD::SELECT &&
7623 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
7626 SmallVector<SDValue, 4> Inputs;
7627 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
7628 SmallPtrSet<SDNode *, 16> Visited;
7630 // Visit all inputs, collect all binary operations (and, or, xor and
7631 // select) that are all fed by truncations.
7632 while (!BinOps.empty()) {
7633 SDValue BinOp = BinOps.back();
7636 if (!Visited.insert(BinOp.getNode()))
7639 PromOps.push_back(BinOp);
7641 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7642 // The condition of the select is not promoted.
7643 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7645 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7648 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7649 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7650 Inputs.push_back(BinOp.getOperand(i));
7651 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7652 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7653 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7654 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7655 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
7656 BinOps.push_back(BinOp.getOperand(i));
7658 // We have an input that is not a truncation or another binary
7659 // operation; we'll abort this transformation.
7665 // Make sure that this is a self-contained cluster of operations (which
7666 // is not quite the same thing as saying that everything has only one
7668 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7669 if (isa<ConstantSDNode>(Inputs[i]))
7672 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7673 UE = Inputs[i].getNode()->use_end();
7676 if (User != N && !Visited.count(User))
7679 // Make sure that we're not going to promote the non-output-value
7680 // operand(s) or SELECT or SELECT_CC.
7681 // FIXME: Although we could sometimes handle this, and it does occur in
7682 // practice that one of the condition inputs to the select is also one of
7683 // the outputs, we currently can't deal with this.
7684 if (User->getOpcode() == ISD::SELECT) {
7685 if (User->getOperand(0) == Inputs[i])
7687 } else if (User->getOpcode() == ISD::SELECT_CC) {
7688 if (User->getOperand(0) == Inputs[i] ||
7689 User->getOperand(1) == Inputs[i])
7695 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7696 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7697 UE = PromOps[i].getNode()->use_end();
7700 if (User != N && !Visited.count(User))
7703 // Make sure that we're not going to promote the non-output-value
7704 // operand(s) or SELECT or SELECT_CC.
7705 // FIXME: Although we could sometimes handle this, and it does occur in
7706 // practice that one of the condition inputs to the select is also one of
7707 // the outputs, we currently can't deal with this.
7708 if (User->getOpcode() == ISD::SELECT) {
7709 if (User->getOperand(0) == PromOps[i])
7711 } else if (User->getOpcode() == ISD::SELECT_CC) {
7712 if (User->getOperand(0) == PromOps[i] ||
7713 User->getOperand(1) == PromOps[i])
7719 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
7720 bool ReallyNeedsExt = false;
7721 if (N->getOpcode() != ISD::ANY_EXTEND) {
7722 // If all of the inputs are not already sign/zero extended, then
7723 // we'll still need to do that at the end.
7724 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7725 if (isa<ConstantSDNode>(Inputs[i]))
7729 Inputs[i].getOperand(0).getValueSizeInBits();
7730 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
7732 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
7733 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
7734 APInt::getHighBitsSet(OpBits,
7735 OpBits-PromBits))) ||
7736 (N->getOpcode() == ISD::SIGN_EXTEND &&
7737 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
7738 (OpBits-(PromBits-1)))) {
7739 ReallyNeedsExt = true;
7745 // Replace all inputs, either with the truncation operand, or a
7746 // truncation or extension to the final output type.
7747 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7748 // Constant inputs need to be replaced with the to-be-promoted nodes that
7749 // use them because they might have users outside of the cluster of
7751 if (isa<ConstantSDNode>(Inputs[i]))
7754 SDValue InSrc = Inputs[i].getOperand(0);
7755 if (Inputs[i].getValueType() == N->getValueType(0))
7756 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
7757 else if (N->getOpcode() == ISD::SIGN_EXTEND)
7758 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7759 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
7760 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7761 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7762 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
7764 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7765 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
7768 // Replace all operations (these are all the same, but have a different
7769 // (promoted) return type). DAG.getNode will validate that the types of
7770 // a binary operator match, so go through the list in reverse so that
7771 // we've likely promoted both operands first.
7772 while (!PromOps.empty()) {
7773 SDValue PromOp = PromOps.back();
7777 switch (PromOp.getOpcode()) {
7778 default: C = 0; break;
7779 case ISD::SELECT: C = 1; break;
7780 case ISD::SELECT_CC: C = 2; break;
7783 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7784 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
7785 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7786 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
7787 // The to-be-promoted operands of this node have not yet been
7788 // promoted (this should be rare because we're going through the
7789 // list backward, but if one of the operands has several users in
7790 // this cluster of to-be-promoted nodes, it is possible).
7791 PromOps.insert(PromOps.begin(), PromOp);
7795 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7796 PromOp.getNode()->op_end());
7798 // If this node has constant inputs, then they'll need to be promoted here.
7799 for (unsigned i = 0; i < 2; ++i) {
7800 if (!isa<ConstantSDNode>(Ops[C+i]))
7802 if (Ops[C+i].getValueType() == N->getValueType(0))
7805 if (N->getOpcode() == ISD::SIGN_EXTEND)
7806 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7807 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7808 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7810 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7813 DAG.ReplaceAllUsesOfValueWith(PromOp,
7814 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
7817 // Now we're left with the initial extension itself.
7818 if (!ReallyNeedsExt)
7819 return N->getOperand(0);
7821 // To zero extend, just mask off everything except for the first bit (in the
7823 if (N->getOpcode() == ISD::ZERO_EXTEND)
7824 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
7825 DAG.getConstant(APInt::getLowBitsSet(
7826 N->getValueSizeInBits(0), PromBits),
7827 N->getValueType(0)));
7829 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
7830 "Invalid extension type");
7831 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
7833 DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
7834 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
7835 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
7836 N->getOperand(0), ShiftCst), ShiftCst);
7839 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
7840 DAGCombinerInfo &DCI) const {
7841 const TargetMachine &TM = getTargetMachine();
7842 SelectionDAG &DAG = DCI.DAG;
7844 switch (N->getOpcode()) {
7847 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7848 if (C->isNullValue()) // 0 << V -> 0.
7849 return N->getOperand(0);
7853 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7854 if (C->isNullValue()) // 0 >>u V -> 0.
7855 return N->getOperand(0);
7859 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7860 if (C->isNullValue() || // 0 >>s V -> 0.
7861 C->isAllOnesValue()) // -1 >>s V -> -1.
7862 return N->getOperand(0);
7865 case ISD::SIGN_EXTEND:
7866 case ISD::ZERO_EXTEND:
7867 case ISD::ANY_EXTEND:
7868 return DAGCombineExtBoolTrunc(N, DCI);
7871 case ISD::SELECT_CC:
7872 return DAGCombineTruncBoolExt(N, DCI);
7874 assert(TM.Options.UnsafeFPMath &&
7875 "Reciprocal estimates require UnsafeFPMath");
7877 if (N->getOperand(1).getOpcode() == ISD::FSQRT) {
7879 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI);
7881 DCI.AddToWorklist(RV.getNode());
7882 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7883 N->getOperand(0), RV);
7885 } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND &&
7886 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7888 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7891 DCI.AddToWorklist(RV.getNode());
7892 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N->getOperand(1)),
7893 N->getValueType(0), RV);
7894 DCI.AddToWorklist(RV.getNode());
7895 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7896 N->getOperand(0), RV);
7898 } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND &&
7899 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7901 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7904 DCI.AddToWorklist(RV.getNode());
7905 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N->getOperand(1)),
7906 N->getValueType(0), RV,
7907 N->getOperand(1).getOperand(1));
7908 DCI.AddToWorklist(RV.getNode());
7909 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7910 N->getOperand(0), RV);
7914 SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI);
7916 DCI.AddToWorklist(RV.getNode());
7917 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7918 N->getOperand(0), RV);
7924 assert(TM.Options.UnsafeFPMath &&
7925 "Reciprocal estimates require UnsafeFPMath");
7927 // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the
7929 SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI);
7931 DCI.AddToWorklist(RV.getNode());
7932 RV = DAGCombineFastRecip(RV, DCI);
7934 // Unfortunately, RV is now NaN if the input was exactly 0. Select out
7935 // this case and force the answer to 0.
7937 EVT VT = RV.getValueType();
7939 SDValue Zero = DAG.getConstantFP(0.0, VT.getScalarType());
7940 if (VT.isVector()) {
7941 assert(VT.getVectorNumElements() == 4 && "Unknown vector type");
7942 Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Zero, Zero, Zero, Zero);
7946 DAG.getSetCC(dl, getSetCCResultType(*DAG.getContext(), VT),
7947 N->getOperand(0), Zero, ISD::SETEQ);
7948 DCI.AddToWorklist(ZeroCmp.getNode());
7949 DCI.AddToWorklist(RV.getNode());
7951 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, dl, VT,
7959 case ISD::SINT_TO_FP:
7960 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
7961 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
7962 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
7963 // We allow the src/dst to be either f32/f64, but the intermediate
7964 // type must be i64.
7965 if (N->getOperand(0).getValueType() == MVT::i64 &&
7966 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
7967 SDValue Val = N->getOperand(0).getOperand(0);
7968 if (Val.getValueType() == MVT::f32) {
7969 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7970 DCI.AddToWorklist(Val.getNode());
7973 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
7974 DCI.AddToWorklist(Val.getNode());
7975 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
7976 DCI.AddToWorklist(Val.getNode());
7977 if (N->getValueType(0) == MVT::f32) {
7978 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
7979 DAG.getIntPtrConstant(0));
7980 DCI.AddToWorklist(Val.getNode());
7983 } else if (N->getOperand(0).getValueType() == MVT::i32) {
7984 // If the intermediate type is i32, we can avoid the load/store here
7991 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
7992 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
7993 !cast<StoreSDNode>(N)->isTruncatingStore() &&
7994 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
7995 N->getOperand(1).getValueType() == MVT::i32 &&
7996 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
7997 SDValue Val = N->getOperand(1).getOperand(0);
7998 if (Val.getValueType() == MVT::f32) {
7999 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8000 DCI.AddToWorklist(Val.getNode());
8002 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
8003 DCI.AddToWorklist(Val.getNode());
8006 N->getOperand(0), Val, N->getOperand(2),
8007 DAG.getValueType(N->getOperand(1).getValueType())
8010 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8011 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
8012 cast<StoreSDNode>(N)->getMemoryVT(),
8013 cast<StoreSDNode>(N)->getMemOperand());
8014 DCI.AddToWorklist(Val.getNode());
8018 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8019 if (cast<StoreSDNode>(N)->isUnindexed() &&
8020 N->getOperand(1).getOpcode() == ISD::BSWAP &&
8021 N->getOperand(1).getNode()->hasOneUse() &&
8022 (N->getOperand(1).getValueType() == MVT::i32 ||
8023 N->getOperand(1).getValueType() == MVT::i16 ||
8024 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8025 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8026 N->getOperand(1).getValueType() == MVT::i64))) {
8027 SDValue BSwapOp = N->getOperand(1).getOperand(0);
8028 // Do an any-extend to 32-bits if this is a half-word input.
8029 if (BSwapOp.getValueType() == MVT::i16)
8030 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8033 N->getOperand(0), BSwapOp, N->getOperand(2),
8034 DAG.getValueType(N->getOperand(1).getValueType())
8037 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8038 Ops, array_lengthof(Ops),
8039 cast<StoreSDNode>(N)->getMemoryVT(),
8040 cast<StoreSDNode>(N)->getMemOperand());
8044 LoadSDNode *LD = cast<LoadSDNode>(N);
8045 EVT VT = LD->getValueType(0);
8046 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8047 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8048 if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
8049 TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
8050 (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8051 VT == MVT::v4i32 || VT == MVT::v4f32) &&
8052 LD->getAlignment() < ABIAlignment) {
8053 // This is a type-legal unaligned Altivec load.
8054 SDValue Chain = LD->getChain();
8055 SDValue Ptr = LD->getBasePtr();
8057 // This implements the loading of unaligned vectors as described in
8058 // the venerable Apple Velocity Engine overview. Specifically:
8059 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8060 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8062 // The general idea is to expand a sequence of one or more unaligned
8063 // loads into a alignment-based permutation-control instruction (lvsl),
8064 // a series of regular vector loads (which always truncate their
8065 // input address to an aligned address), and a series of permutations.
8066 // The results of these permutations are the requested loaded values.
8067 // The trick is that the last "extra" load is not taken from the address
8068 // you might suspect (sizeof(vector) bytes after the last requested
8069 // load), but rather sizeof(vector) - 1 bytes after the last
8070 // requested vector. The point of this is to avoid a page fault if the
8071 // base address happened to be aligned. This works because if the base
8072 // address is aligned, then adding less than a full vector length will
8073 // cause the last vector in the sequence to be (re)loaded. Otherwise,
8074 // the next vector will be fetched as you might suspect was necessary.
8076 // We might be able to reuse the permutation generation from
8077 // a different base address offset from this one by an aligned amount.
8078 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8079 // optimization later.
8080 SDValue PermCntl = BuildIntrinsicOp(Intrinsic::ppc_altivec_lvsl, Ptr,
8081 DAG, dl, MVT::v16i8);
8083 // Refine the alignment of the original load (a "new" load created here
8084 // which was identical to the first except for the alignment would be
8085 // merged with the existing node regardless).
8086 MachineFunction &MF = DAG.getMachineFunction();
8087 MachineMemOperand *MMO =
8088 MF.getMachineMemOperand(LD->getPointerInfo(),
8089 LD->getMemOperand()->getFlags(),
8090 LD->getMemoryVT().getStoreSize(),
8092 LD->refineAlignment(MMO);
8093 SDValue BaseLoad = SDValue(LD, 0);
8095 // Note that the value of IncOffset (which is provided to the next
8096 // load's pointer info offset value, and thus used to calculate the
8097 // alignment), and the value of IncValue (which is actually used to
8098 // increment the pointer value) are different! This is because we
8099 // require the next load to appear to be aligned, even though it
8100 // is actually offset from the base pointer by a lesser amount.
8101 int IncOffset = VT.getSizeInBits() / 8;
8102 int IncValue = IncOffset;
8104 // Walk (both up and down) the chain looking for another load at the real
8105 // (aligned) offset (the alignment of the other load does not matter in
8106 // this case). If found, then do not use the offset reduction trick, as
8107 // that will prevent the loads from being later combined (as they would
8108 // otherwise be duplicates).
8109 if (!findConsecutiveLoad(LD, DAG))
8112 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
8113 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
8116 DAG.getLoad(VT, dl, Chain, Ptr,
8117 LD->getPointerInfo().getWithOffset(IncOffset),
8118 LD->isVolatile(), LD->isNonTemporal(),
8119 LD->isInvariant(), ABIAlignment);
8121 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8122 BaseLoad.getValue(1), ExtraLoad.getValue(1));
8124 if (BaseLoad.getValueType() != MVT::v4i32)
8125 BaseLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, BaseLoad);
8127 if (ExtraLoad.getValueType() != MVT::v4i32)
8128 ExtraLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, ExtraLoad);
8130 SDValue Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8131 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
8133 if (VT != MVT::v4i32)
8134 Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
8136 // Now we need to be really careful about how we update the users of the
8137 // original load. We cannot just call DCI.CombineTo (or
8138 // DAG.ReplaceAllUsesWith for that matter), because the load still has
8139 // uses created here (the permutation for example) that need to stay.
8140 SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
8142 SDUse &Use = UI.getUse();
8144 // Note: BaseLoad is checked here because it might not be N, but a
8146 if (User == Perm.getNode() || User == BaseLoad.getNode() ||
8147 User == TF.getNode() || Use.getResNo() > 1) {
8152 SDValue To = Use.getResNo() ? TF : Perm;
8155 SmallVector<SDValue, 8> Ops;
8156 for (SDNode::op_iterator O = User->op_begin(),
8157 OE = User->op_end(); O != OE; ++O) {
8164 DAG.UpdateNodeOperands(User, Ops.data(), Ops.size());
8167 return SDValue(N, 0);
8171 case ISD::INTRINSIC_WO_CHAIN:
8172 if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() ==
8173 Intrinsic::ppc_altivec_lvsl &&
8174 N->getOperand(1)->getOpcode() == ISD::ADD) {
8175 SDValue Add = N->getOperand(1);
8177 if (DAG.MaskedValueIsZero(Add->getOperand(1),
8178 APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8179 Add.getValueType().getScalarType().getSizeInBits()))) {
8180 SDNode *BasePtr = Add->getOperand(0).getNode();
8181 for (SDNode::use_iterator UI = BasePtr->use_begin(),
8182 UE = BasePtr->use_end(); UI != UE; ++UI) {
8183 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8184 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8185 Intrinsic::ppc_altivec_lvsl) {
8186 // We've found another LVSL, and this address if an aligned
8187 // multiple of that one. The results will be the same, so use the
8188 // one we've just found instead.
8190 return SDValue(*UI, 0);
8198 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8199 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8200 N->getOperand(0).hasOneUse() &&
8201 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8202 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8203 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8204 N->getValueType(0) == MVT::i64))) {
8205 SDValue Load = N->getOperand(0);
8206 LoadSDNode *LD = cast<LoadSDNode>(Load);
8207 // Create the byte-swapping load.
8209 LD->getChain(), // Chain
8210 LD->getBasePtr(), // Ptr
8211 DAG.getValueType(N->getValueType(0)) // VT
8214 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8215 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8216 MVT::i64 : MVT::i32, MVT::Other),
8217 Ops, 3, LD->getMemoryVT(), LD->getMemOperand());
8219 // If this is an i16 load, insert the truncate.
8220 SDValue ResVal = BSLoad;
8221 if (N->getValueType(0) == MVT::i16)
8222 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8224 // First, combine the bswap away. This makes the value produced by the
8226 DCI.CombineTo(N, ResVal);
8228 // Next, combine the load away, we give it a bogus result value but a real
8229 // chain result. The result value is dead because the bswap is dead.
8230 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8232 // Return N so it doesn't get rechecked!
8233 return SDValue(N, 0);
8237 case PPCISD::VCMP: {
8238 // If a VCMPo node already exists with exactly the same operands as this
8239 // node, use its result instead of this node (VCMPo computes both a CR6 and
8240 // a normal output).
8242 if (!N->getOperand(0).hasOneUse() &&
8243 !N->getOperand(1).hasOneUse() &&
8244 !N->getOperand(2).hasOneUse()) {
8246 // Scan all of the users of the LHS, looking for VCMPo's that match.
8247 SDNode *VCMPoNode = nullptr;
8249 SDNode *LHSN = N->getOperand(0).getNode();
8250 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8252 if (UI->getOpcode() == PPCISD::VCMPo &&
8253 UI->getOperand(1) == N->getOperand(1) &&
8254 UI->getOperand(2) == N->getOperand(2) &&
8255 UI->getOperand(0) == N->getOperand(0)) {
8260 // If there is no VCMPo node, or if the flag value has a single use, don't
8262 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8265 // Look at the (necessarily single) use of the flag value. If it has a
8266 // chain, this transformation is more complex. Note that multiple things
8267 // could use the value result, which we should ignore.
8268 SDNode *FlagUser = nullptr;
8269 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8270 FlagUser == nullptr; ++UI) {
8271 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8273 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8274 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8281 // If the user is a MFOCRF instruction, we know this is safe.
8282 // Otherwise we give up for right now.
8283 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
8284 return SDValue(VCMPoNode, 0);
8289 SDValue Cond = N->getOperand(1);
8290 SDValue Target = N->getOperand(2);
8292 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8293 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
8294 Intrinsic::ppc_is_decremented_ctr_nonzero) {
8296 // We now need to make the intrinsic dead (it cannot be instruction
8298 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
8299 assert(Cond.getNode()->hasOneUse() &&
8300 "Counter decrement has more than one use");
8302 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
8303 N->getOperand(0), Target);
8308 // If this is a branch on an altivec predicate comparison, lower this so
8309 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
8310 // lowering is done pre-legalize, because the legalizer lowers the predicate
8311 // compare down to code that is difficult to reassemble.
8312 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
8313 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
8315 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
8316 // value. If so, pass-through the AND to get to the intrinsic.
8317 if (LHS.getOpcode() == ISD::AND &&
8318 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8319 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
8320 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8321 isa<ConstantSDNode>(LHS.getOperand(1)) &&
8322 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
8324 LHS = LHS.getOperand(0);
8326 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8327 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
8328 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8329 isa<ConstantSDNode>(RHS)) {
8330 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8331 "Counter decrement comparison is not EQ or NE");
8333 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8334 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
8335 (CC == ISD::SETNE && !Val);
8337 // We now need to make the intrinsic dead (it cannot be instruction
8339 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
8340 assert(LHS.getNode()->hasOneUse() &&
8341 "Counter decrement has more than one use");
8343 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
8344 N->getOperand(0), N->getOperand(4));
8350 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8351 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
8352 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
8353 assert(isDot && "Can't compare against a vector result!");
8355 // If this is a comparison against something other than 0/1, then we know
8356 // that the condition is never/always true.
8357 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8358 if (Val != 0 && Val != 1) {
8359 if (CC == ISD::SETEQ) // Cond never true, remove branch.
8360 return N->getOperand(0);
8361 // Always !=, turn it into an unconditional branch.
8362 return DAG.getNode(ISD::BR, dl, MVT::Other,
8363 N->getOperand(0), N->getOperand(4));
8366 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
8368 // Create the PPCISD altivec 'dot' comparison node.
8370 LHS.getOperand(2), // LHS of compare
8371 LHS.getOperand(3), // RHS of compare
8372 DAG.getConstant(CompareOpc, MVT::i32)
8374 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
8375 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8377 // Unpack the result based on how the target uses it.
8378 PPC::Predicate CompOpc;
8379 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
8380 default: // Can't happen, don't crash on invalid number though.
8381 case 0: // Branch on the value of the EQ bit of CR6.
8382 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
8384 case 1: // Branch on the inverted value of the EQ bit of CR6.
8385 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
8387 case 2: // Branch on the value of the LT bit of CR6.
8388 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
8390 case 3: // Branch on the inverted value of the LT bit of CR6.
8391 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
8395 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
8396 DAG.getConstant(CompOpc, MVT::i32),
8397 DAG.getRegister(PPC::CR6, MVT::i32),
8398 N->getOperand(4), CompNode.getValue(1));
8407 //===----------------------------------------------------------------------===//
8408 // Inline Assembly Support
8409 //===----------------------------------------------------------------------===//
8411 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8414 const SelectionDAG &DAG,
8415 unsigned Depth) const {
8416 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
8417 switch (Op.getOpcode()) {
8419 case PPCISD::LBRX: {
8420 // lhbrx is known to have the top bits cleared out.
8421 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
8422 KnownZero = 0xFFFF0000;
8425 case ISD::INTRINSIC_WO_CHAIN: {
8426 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
8428 case Intrinsic::ppc_altivec_vcmpbfp_p:
8429 case Intrinsic::ppc_altivec_vcmpeqfp_p:
8430 case Intrinsic::ppc_altivec_vcmpequb_p:
8431 case Intrinsic::ppc_altivec_vcmpequh_p:
8432 case Intrinsic::ppc_altivec_vcmpequw_p:
8433 case Intrinsic::ppc_altivec_vcmpgefp_p:
8434 case Intrinsic::ppc_altivec_vcmpgtfp_p:
8435 case Intrinsic::ppc_altivec_vcmpgtsb_p:
8436 case Intrinsic::ppc_altivec_vcmpgtsh_p:
8437 case Intrinsic::ppc_altivec_vcmpgtsw_p:
8438 case Intrinsic::ppc_altivec_vcmpgtub_p:
8439 case Intrinsic::ppc_altivec_vcmpgtuh_p:
8440 case Intrinsic::ppc_altivec_vcmpgtuw_p:
8441 KnownZero = ~1U; // All bits but the low one are known to be zero.
8449 /// getConstraintType - Given a constraint, return the type of
8450 /// constraint it is for this target.
8451 PPCTargetLowering::ConstraintType
8452 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
8453 if (Constraint.size() == 1) {
8454 switch (Constraint[0]) {
8461 return C_RegisterClass;
8463 // FIXME: While Z does indicate a memory constraint, it specifically
8464 // indicates an r+r address (used in conjunction with the 'y' modifier
8465 // in the replacement string). Currently, we're forcing the base
8466 // register to be r0 in the asm printer (which is interpreted as zero)
8467 // and forming the complete address in the second register. This is
8471 } else if (Constraint == "wc") { // individual CR bits.
8472 return C_RegisterClass;
8473 } else if (Constraint == "wa" || Constraint == "wd" ||
8474 Constraint == "wf" || Constraint == "ws") {
8475 return C_RegisterClass; // VSX registers.
8477 return TargetLowering::getConstraintType(Constraint);
8480 /// Examine constraint type and operand type and determine a weight value.
8481 /// This object must already have been set up with the operand type
8482 /// and the current alternative constraint selected.
8483 TargetLowering::ConstraintWeight
8484 PPCTargetLowering::getSingleConstraintMatchWeight(
8485 AsmOperandInfo &info, const char *constraint) const {
8486 ConstraintWeight weight = CW_Invalid;
8487 Value *CallOperandVal = info.CallOperandVal;
8488 // If we don't have a value, we can't do a match,
8489 // but allow it at the lowest weight.
8490 if (!CallOperandVal)
8492 Type *type = CallOperandVal->getType();
8494 // Look at the constraint type.
8495 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
8496 return CW_Register; // an individual CR bit.
8497 else if ((StringRef(constraint) == "wa" ||
8498 StringRef(constraint) == "wd" ||
8499 StringRef(constraint) == "wf") &&
8502 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
8505 switch (*constraint) {
8507 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8510 if (type->isIntegerTy())
8511 weight = CW_Register;
8514 if (type->isFloatTy())
8515 weight = CW_Register;
8518 if (type->isDoubleTy())
8519 weight = CW_Register;
8522 if (type->isVectorTy())
8523 weight = CW_Register;
8526 weight = CW_Register;
8535 std::pair<unsigned, const TargetRegisterClass*>
8536 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8538 if (Constraint.size() == 1) {
8539 // GCC RS6000 Constraint Letters
8540 switch (Constraint[0]) {
8542 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8543 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
8544 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
8546 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8547 return std::make_pair(0U, &PPC::G8RCRegClass);
8548 return std::make_pair(0U, &PPC::GPRCRegClass);
8550 if (VT == MVT::f32 || VT == MVT::i32)
8551 return std::make_pair(0U, &PPC::F4RCRegClass);
8552 if (VT == MVT::f64 || VT == MVT::i64)
8553 return std::make_pair(0U, &PPC::F8RCRegClass);
8556 return std::make_pair(0U, &PPC::VRRCRegClass);
8558 return std::make_pair(0U, &PPC::CRRCRegClass);
8560 } else if (Constraint == "wc") { // an individual CR bit.
8561 return std::make_pair(0U, &PPC::CRBITRCRegClass);
8562 } else if (Constraint == "wa" || Constraint == "wd" ||
8563 Constraint == "wf") {
8564 return std::make_pair(0U, &PPC::VSRCRegClass);
8565 } else if (Constraint == "ws") {
8566 return std::make_pair(0U, &PPC::VSFRCRegClass);
8569 std::pair<unsigned, const TargetRegisterClass*> R =
8570 TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8572 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
8573 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
8574 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
8576 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
8577 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
8578 if (R.first && VT == MVT::i64 && PPCSubTarget.isPPC64() &&
8579 PPC::GPRCRegClass.contains(R.first)) {
8580 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
8581 return std::make_pair(TRI->getMatchingSuperReg(R.first,
8582 PPC::sub_32, &PPC::G8RCRegClass),
8583 &PPC::G8RCRegClass);
8590 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8591 /// vector. If it is invalid, don't add anything to Ops.
8592 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8593 std::string &Constraint,
8594 std::vector<SDValue>&Ops,
8595 SelectionDAG &DAG) const {
8598 // Only support length 1 constraints.
8599 if (Constraint.length() > 1) return;
8601 char Letter = Constraint[0];
8612 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
8613 if (!CST) return; // Must be an immediate to match.
8614 unsigned Value = CST->getZExtValue();
8616 default: llvm_unreachable("Unknown constraint letter!");
8617 case 'I': // "I" is a signed 16-bit constant.
8618 if ((short)Value == (int)Value)
8619 Result = DAG.getTargetConstant(Value, Op.getValueType());
8621 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
8622 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
8623 if ((short)Value == 0)
8624 Result = DAG.getTargetConstant(Value, Op.getValueType());
8626 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
8627 if ((Value >> 16) == 0)
8628 Result = DAG.getTargetConstant(Value, Op.getValueType());
8630 case 'M': // "M" is a constant that is greater than 31.
8632 Result = DAG.getTargetConstant(Value, Op.getValueType());
8634 case 'N': // "N" is a positive constant that is an exact power of two.
8635 if ((int)Value > 0 && isPowerOf2_32(Value))
8636 Result = DAG.getTargetConstant(Value, Op.getValueType());
8638 case 'O': // "O" is the constant zero.
8640 Result = DAG.getTargetConstant(Value, Op.getValueType());
8642 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
8643 if ((short)-Value == (int)-Value)
8644 Result = DAG.getTargetConstant(Value, Op.getValueType());
8651 if (Result.getNode()) {
8652 Ops.push_back(Result);
8656 // Handle standard constraint letters.
8657 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
8660 // isLegalAddressingMode - Return true if the addressing mode represented
8661 // by AM is legal for this target, for a load/store of the specified type.
8662 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8664 // FIXME: PPC does not allow r+i addressing modes for vectors!
8666 // PPC allows a sign-extended 16-bit immediate field.
8667 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
8670 // No global is ever allowed as a base.
8674 // PPC only support r+r,
8676 case 0: // "r+i" or just "i", depending on HasBaseReg.
8679 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
8681 // Otherwise we have r+r or r+i.
8684 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
8686 // Allow 2*r as r+r.
8689 // No other scales are supported.
8696 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
8697 SelectionDAG &DAG) const {
8698 MachineFunction &MF = DAG.getMachineFunction();
8699 MachineFrameInfo *MFI = MF.getFrameInfo();
8700 MFI->setReturnAddressIsTaken(true);
8702 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
8706 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8708 // Make sure the function does not optimize away the store of the RA to
8710 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
8711 FuncInfo->setLRStoreRequired();
8712 bool isPPC64 = PPCSubTarget.isPPC64();
8713 bool isDarwinABI = PPCSubTarget.isDarwinABI();
8716 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8719 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
8720 isPPC64? MVT::i64 : MVT::i32);
8721 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8722 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8724 MachinePointerInfo(), false, false, false, 0);
8727 // Just load the return address off the stack.
8728 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
8729 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8730 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
8733 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
8734 SelectionDAG &DAG) const {
8736 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8738 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
8739 bool isPPC64 = PtrVT == MVT::i64;
8741 MachineFunction &MF = DAG.getMachineFunction();
8742 MachineFrameInfo *MFI = MF.getFrameInfo();
8743 MFI->setFrameAddressIsTaken(true);
8745 // Naked functions never have a frame pointer, and so we use r1. For all
8746 // other functions, this decision must be delayed until during PEI.
8748 if (MF.getFunction()->getAttributes().hasAttribute(
8749 AttributeSet::FunctionIndex, Attribute::Naked))
8750 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
8752 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
8754 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
8757 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
8758 FrameAddr, MachinePointerInfo(), false, false,
8764 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
8765 // The PowerPC target isn't yet aware of offsets.
8769 /// getOptimalMemOpType - Returns the target specific optimal type for load
8770 /// and store operations as a result of memset, memcpy, and memmove
8771 /// lowering. If DstAlign is zero that means it's safe to destination
8772 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
8773 /// means there isn't a need to check it against alignment requirement,
8774 /// probably because the source does not need to be loaded. If 'IsMemset' is
8775 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
8776 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
8777 /// source is constant so it does not need to be loaded.
8778 /// It returns EVT::Other if the type should be determined using generic
8779 /// target-independent logic.
8780 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
8781 unsigned DstAlign, unsigned SrcAlign,
8782 bool IsMemset, bool ZeroMemset,
8784 MachineFunction &MF) const {
8785 if (this->PPCSubTarget.isPPC64()) {
8792 /// \brief Returns true if it is beneficial to convert a load of a constant
8793 /// to just the constant itself.
8794 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
8796 assert(Ty->isIntegerTy());
8798 unsigned BitSize = Ty->getPrimitiveSizeInBits();
8799 if (BitSize == 0 || BitSize > 64)
8804 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8805 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8807 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8808 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8809 return NumBits1 == 64 && NumBits2 == 32;
8812 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8813 if (!VT1.isInteger() || !VT2.isInteger())
8815 unsigned NumBits1 = VT1.getSizeInBits();
8816 unsigned NumBits2 = VT2.getSizeInBits();
8817 return NumBits1 == 64 && NumBits2 == 32;
8820 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
8821 return isInt<16>(Imm) || isUInt<16>(Imm);
8824 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
8825 return isInt<16>(Imm) || isUInt<16>(Imm);
8828 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
8831 if (DisablePPCUnaligned)
8834 // PowerPC supports unaligned memory access for simple non-vector types.
8835 // Although accessing unaligned addresses is not as efficient as accessing
8836 // aligned addresses, it is generally more efficient than manual expansion,
8837 // and generally only traps for software emulation when crossing page
8843 if (VT.getSimpleVT().isVector()) {
8844 if (PPCSubTarget.hasVSX()) {
8845 if (VT != MVT::v2f64 && VT != MVT::v2i64)
8852 if (VT == MVT::ppcf128)
8861 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8862 VT = VT.getScalarType();
8867 switch (VT.getSimpleVT().SimpleTy) {
8879 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
8880 EVT VT , unsigned DefinedValues) const {
8881 if (VT == MVT::v2i64)
8884 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
8887 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
8888 if (DisableILPPref || PPCSubTarget.enableMachineScheduler())
8889 return TargetLowering::getSchedulingPreference(N);
8894 // Create a fast isel object.
8896 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
8897 const TargetLibraryInfo *LibInfo) const {
8898 return PPC::createFastISel(FuncInfo, LibInfo);