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/ADT/StringSwitch.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/SelectionDAG.h"
28 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
29 #include "llvm/IR/CallingConv.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetOptions.h"
41 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
42 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
44 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
45 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
47 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
48 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
50 // FIXME: Remove this once the bug has been fixed!
51 extern cl::opt<bool> ANDIGlueBug;
53 static TargetLoweringObjectFile *createTLOF(const PPCTargetMachine &TM) {
54 if (TM.getSubtargetImpl()->isDarwin())
55 return new TargetLoweringObjectFileMachO();
57 return new PPC64LinuxTargetObjectFile();
60 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
61 : TargetLowering(TM, createTLOF(TM)), PPCSubTarget(*TM.getSubtargetImpl()) {
62 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
66 // Use _setjmp/_longjmp instead of setjmp/longjmp.
67 setUseUnderscoreSetJmp(true);
68 setUseUnderscoreLongJmp(true);
70 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
71 // arguments are at least 4/8 bytes aligned.
72 bool isPPC64 = Subtarget->isPPC64();
73 setMinStackArgumentAlignment(isPPC64 ? 8:4);
75 // Set up the register classes.
76 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
77 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
78 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
80 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
81 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
82 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
84 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
86 // PowerPC has pre-inc load and store's.
87 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
88 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
89 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
90 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
91 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
92 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
93 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
94 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
95 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
96 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
98 if (Subtarget->useCRBits()) {
99 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
101 if (isPPC64 || Subtarget->hasFPCVT()) {
102 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
103 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
104 isPPC64 ? MVT::i64 : MVT::i32);
105 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
106 AddPromotedToType (ISD::UINT_TO_FP, MVT::i1,
107 isPPC64 ? MVT::i64 : MVT::i32);
109 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
110 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
113 // PowerPC does not support direct load / store of condition registers
114 setOperationAction(ISD::LOAD, MVT::i1, Custom);
115 setOperationAction(ISD::STORE, MVT::i1, Custom);
117 // FIXME: Remove this once the ANDI glue bug is fixed:
119 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
121 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
122 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
123 setTruncStoreAction(MVT::i64, MVT::i1, Expand);
124 setTruncStoreAction(MVT::i32, MVT::i1, Expand);
125 setTruncStoreAction(MVT::i16, MVT::i1, Expand);
126 setTruncStoreAction(MVT::i8, MVT::i1, Expand);
128 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
131 // This is used in the ppcf128->int sequence. Note it has different semantics
132 // from FP_ROUND: that rounds to nearest, this rounds to zero.
133 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
135 // We do not currently implement these libm ops for PowerPC.
136 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
137 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
138 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
139 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
140 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
141 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
143 // PowerPC has no SREM/UREM instructions
144 setOperationAction(ISD::SREM, MVT::i32, Expand);
145 setOperationAction(ISD::UREM, MVT::i32, Expand);
146 setOperationAction(ISD::SREM, MVT::i64, Expand);
147 setOperationAction(ISD::UREM, MVT::i64, Expand);
149 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
150 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
151 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
152 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
153 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
154 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
155 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
156 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
157 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
159 // We don't support sin/cos/sqrt/fmod/pow
160 setOperationAction(ISD::FSIN , MVT::f64, Expand);
161 setOperationAction(ISD::FCOS , MVT::f64, Expand);
162 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
163 setOperationAction(ISD::FREM , MVT::f64, Expand);
164 setOperationAction(ISD::FPOW , MVT::f64, Expand);
165 setOperationAction(ISD::FMA , MVT::f64, Legal);
166 setOperationAction(ISD::FSIN , MVT::f32, Expand);
167 setOperationAction(ISD::FCOS , MVT::f32, Expand);
168 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
169 setOperationAction(ISD::FREM , MVT::f32, Expand);
170 setOperationAction(ISD::FPOW , MVT::f32, Expand);
171 setOperationAction(ISD::FMA , MVT::f32, Legal);
173 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
175 // If we're enabling GP optimizations, use hardware square root
176 if (!Subtarget->hasFSQRT() &&
177 !(TM.Options.UnsafeFPMath &&
178 Subtarget->hasFRSQRTE() && Subtarget->hasFRE()))
179 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
181 if (!Subtarget->hasFSQRT() &&
182 !(TM.Options.UnsafeFPMath &&
183 Subtarget->hasFRSQRTES() && Subtarget->hasFRES()))
184 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
186 if (Subtarget->hasFCPSGN()) {
187 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
188 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
190 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
191 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
194 if (Subtarget->hasFPRND()) {
195 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
196 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
197 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
198 setOperationAction(ISD::FROUND, MVT::f64, Legal);
200 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
201 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
202 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
203 setOperationAction(ISD::FROUND, MVT::f32, Legal);
206 // PowerPC does not have BSWAP, CTPOP or CTTZ
207 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
208 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
209 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
210 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
211 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
212 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
213 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
214 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
216 if (Subtarget->hasPOPCNTD()) {
217 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
218 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
220 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
221 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
224 // PowerPC does not have ROTR
225 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
226 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
228 if (!Subtarget->useCRBits()) {
229 // PowerPC does not have Select
230 setOperationAction(ISD::SELECT, MVT::i32, Expand);
231 setOperationAction(ISD::SELECT, MVT::i64, Expand);
232 setOperationAction(ISD::SELECT, MVT::f32, Expand);
233 setOperationAction(ISD::SELECT, MVT::f64, Expand);
236 // PowerPC wants to turn select_cc of FP into fsel when possible.
237 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
238 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
240 // PowerPC wants to optimize integer setcc a bit
241 if (!Subtarget->useCRBits())
242 setOperationAction(ISD::SETCC, MVT::i32, Custom);
244 // PowerPC does not have BRCOND which requires SetCC
245 if (!Subtarget->useCRBits())
246 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
248 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
250 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
251 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
253 // PowerPC does not have [U|S]INT_TO_FP
254 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
255 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
257 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
258 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
259 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
260 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
262 // We cannot sextinreg(i1). Expand to shifts.
263 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
265 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
266 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
267 // support continuation, user-level threading, and etc.. As a result, no
268 // other SjLj exception interfaces are implemented and please don't build
269 // your own exception handling based on them.
270 // LLVM/Clang supports zero-cost DWARF exception handling.
271 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
272 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
274 // We want to legalize GlobalAddress and ConstantPool nodes into the
275 // appropriate instructions to materialize the address.
276 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
277 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
278 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
279 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
280 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
281 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
282 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
283 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
284 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
285 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
288 setOperationAction(ISD::TRAP, MVT::Other, Legal);
290 // TRAMPOLINE is custom lowered.
291 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
292 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
294 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
295 setOperationAction(ISD::VASTART , MVT::Other, Custom);
297 if (Subtarget->isSVR4ABI()) {
299 // VAARG always uses double-word chunks, so promote anything smaller.
300 setOperationAction(ISD::VAARG, MVT::i1, Promote);
301 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
302 setOperationAction(ISD::VAARG, MVT::i8, Promote);
303 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
304 setOperationAction(ISD::VAARG, MVT::i16, Promote);
305 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
306 setOperationAction(ISD::VAARG, MVT::i32, Promote);
307 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
308 setOperationAction(ISD::VAARG, MVT::Other, Expand);
310 // VAARG is custom lowered with the 32-bit SVR4 ABI.
311 setOperationAction(ISD::VAARG, MVT::Other, Custom);
312 setOperationAction(ISD::VAARG, MVT::i64, Custom);
315 setOperationAction(ISD::VAARG, MVT::Other, Expand);
317 if (Subtarget->isSVR4ABI() && !isPPC64)
318 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
319 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
321 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
323 // Use the default implementation.
324 setOperationAction(ISD::VAEND , MVT::Other, Expand);
325 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
326 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
327 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
328 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
330 // We want to custom lower some of our intrinsics.
331 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
333 // To handle counter-based loop conditions.
334 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
336 // Comparisons that require checking two conditions.
337 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
338 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
339 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
340 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
341 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
342 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
343 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
344 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
345 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
346 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
347 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
348 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
350 if (Subtarget->has64BitSupport()) {
351 // They also have instructions for converting between i64 and fp.
352 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
353 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
354 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
355 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
356 // This is just the low 32 bits of a (signed) fp->i64 conversion.
357 // We cannot do this with Promote because i64 is not a legal type.
358 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
360 if (PPCSubTarget.hasLFIWAX() || Subtarget->isPPC64())
361 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
363 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
364 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
367 // With the instructions enabled under FPCVT, we can do everything.
368 if (PPCSubTarget.hasFPCVT()) {
369 if (Subtarget->has64BitSupport()) {
370 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
371 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
372 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
373 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
376 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
377 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
378 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
379 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
382 if (Subtarget->use64BitRegs()) {
383 // 64-bit PowerPC implementations can support i64 types directly
384 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
385 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
386 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
387 // 64-bit PowerPC wants to expand i128 shifts itself.
388 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
389 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
390 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
392 // 32-bit PowerPC wants to expand i64 shifts itself.
393 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
394 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
395 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
398 if (Subtarget->hasAltivec()) {
399 // First set operation action for all vector types to expand. Then we
400 // will selectively turn on ones that can be effectively codegen'd.
401 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
402 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
403 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
405 // add/sub are legal for all supported vector VT's.
406 setOperationAction(ISD::ADD , VT, Legal);
407 setOperationAction(ISD::SUB , VT, Legal);
409 // We promote all shuffles to v16i8.
410 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
411 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
413 // We promote all non-typed operations to v4i32.
414 setOperationAction(ISD::AND , VT, Promote);
415 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
416 setOperationAction(ISD::OR , VT, Promote);
417 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
418 setOperationAction(ISD::XOR , VT, Promote);
419 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
420 setOperationAction(ISD::LOAD , VT, Promote);
421 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
422 setOperationAction(ISD::SELECT, VT, Promote);
423 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
424 setOperationAction(ISD::STORE, VT, Promote);
425 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
427 // No other operations are legal.
428 setOperationAction(ISD::MUL , VT, Expand);
429 setOperationAction(ISD::SDIV, VT, Expand);
430 setOperationAction(ISD::SREM, VT, Expand);
431 setOperationAction(ISD::UDIV, VT, Expand);
432 setOperationAction(ISD::UREM, VT, Expand);
433 setOperationAction(ISD::FDIV, VT, Expand);
434 setOperationAction(ISD::FREM, VT, Expand);
435 setOperationAction(ISD::FNEG, VT, Expand);
436 setOperationAction(ISD::FSQRT, VT, Expand);
437 setOperationAction(ISD::FLOG, VT, Expand);
438 setOperationAction(ISD::FLOG10, VT, Expand);
439 setOperationAction(ISD::FLOG2, VT, Expand);
440 setOperationAction(ISD::FEXP, VT, Expand);
441 setOperationAction(ISD::FEXP2, VT, Expand);
442 setOperationAction(ISD::FSIN, VT, Expand);
443 setOperationAction(ISD::FCOS, VT, Expand);
444 setOperationAction(ISD::FABS, VT, Expand);
445 setOperationAction(ISD::FPOWI, VT, Expand);
446 setOperationAction(ISD::FFLOOR, VT, Expand);
447 setOperationAction(ISD::FCEIL, VT, Expand);
448 setOperationAction(ISD::FTRUNC, VT, Expand);
449 setOperationAction(ISD::FRINT, VT, Expand);
450 setOperationAction(ISD::FNEARBYINT, VT, Expand);
451 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
452 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
453 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
454 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
455 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
456 setOperationAction(ISD::UDIVREM, VT, Expand);
457 setOperationAction(ISD::SDIVREM, VT, Expand);
458 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
459 setOperationAction(ISD::FPOW, VT, Expand);
460 setOperationAction(ISD::BSWAP, VT, Expand);
461 setOperationAction(ISD::CTPOP, VT, Expand);
462 setOperationAction(ISD::CTLZ, VT, Expand);
463 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
464 setOperationAction(ISD::CTTZ, VT, Expand);
465 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
466 setOperationAction(ISD::VSELECT, VT, Expand);
467 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
469 for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
470 j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
471 MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
472 setTruncStoreAction(VT, InnerVT, Expand);
474 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
475 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
476 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
479 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
480 // with merges, splats, etc.
481 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
483 setOperationAction(ISD::AND , MVT::v4i32, Legal);
484 setOperationAction(ISD::OR , MVT::v4i32, Legal);
485 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
486 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
487 setOperationAction(ISD::SELECT, MVT::v4i32,
488 Subtarget->useCRBits() ? Legal : Expand);
489 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
490 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
491 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
492 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
493 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
494 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
495 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
496 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
497 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
499 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
500 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
501 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
502 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
504 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
505 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
507 if (TM.Options.UnsafeFPMath || Subtarget->hasVSX()) {
508 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
509 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
512 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
513 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
514 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
516 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
517 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
519 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
520 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
521 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
522 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
524 // Altivec does not contain unordered floating-point compare instructions
525 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
526 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
527 setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand);
528 setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand);
529 setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand);
530 setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand);
532 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
533 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
535 if (Subtarget->hasVSX()) {
536 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
537 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
539 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
540 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
541 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
542 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
543 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
545 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
547 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
548 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
550 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
551 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
553 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
554 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
555 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
556 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
557 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
559 // Share the Altivec comparison restrictions.
560 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
561 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
562 setCondCodeAction(ISD::SETUGT, MVT::v2f64, Expand);
563 setCondCodeAction(ISD::SETUGE, MVT::v2f64, Expand);
564 setCondCodeAction(ISD::SETULT, MVT::v2f64, Expand);
565 setCondCodeAction(ISD::SETULE, MVT::v2f64, Expand);
567 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
568 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
570 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
571 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
573 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
575 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
577 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
578 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
580 // VSX v2i64 only supports non-arithmetic operations.
581 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
582 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
584 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
585 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
586 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
588 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
590 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
591 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
592 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
593 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
595 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
597 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
598 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
599 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
600 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
602 // Vector operation legalization checks the result type of
603 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
604 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
605 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
606 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
607 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
609 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
613 if (Subtarget->has64BitSupport()) {
614 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
615 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
618 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
619 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
620 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
621 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
623 setBooleanContents(ZeroOrOneBooleanContent);
624 // Altivec instructions set fields to all zeros or all ones.
625 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
628 setStackPointerRegisterToSaveRestore(PPC::X1);
629 setExceptionPointerRegister(PPC::X3);
630 setExceptionSelectorRegister(PPC::X4);
632 setStackPointerRegisterToSaveRestore(PPC::R1);
633 setExceptionPointerRegister(PPC::R3);
634 setExceptionSelectorRegister(PPC::R4);
637 // We have target-specific dag combine patterns for the following nodes:
638 setTargetDAGCombine(ISD::SINT_TO_FP);
639 setTargetDAGCombine(ISD::LOAD);
640 setTargetDAGCombine(ISD::STORE);
641 setTargetDAGCombine(ISD::BR_CC);
642 if (Subtarget->useCRBits())
643 setTargetDAGCombine(ISD::BRCOND);
644 setTargetDAGCombine(ISD::BSWAP);
645 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
647 setTargetDAGCombine(ISD::SIGN_EXTEND);
648 setTargetDAGCombine(ISD::ZERO_EXTEND);
649 setTargetDAGCombine(ISD::ANY_EXTEND);
651 if (Subtarget->useCRBits()) {
652 setTargetDAGCombine(ISD::TRUNCATE);
653 setTargetDAGCombine(ISD::SETCC);
654 setTargetDAGCombine(ISD::SELECT_CC);
657 // Use reciprocal estimates.
658 if (TM.Options.UnsafeFPMath) {
659 setTargetDAGCombine(ISD::FDIV);
660 setTargetDAGCombine(ISD::FSQRT);
663 // Darwin long double math library functions have $LDBL128 appended.
664 if (Subtarget->isDarwin()) {
665 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
666 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
667 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
668 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
669 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
670 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
671 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
672 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
673 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
674 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
677 // With 32 condition bits, we don't need to sink (and duplicate) compares
678 // aggressively in CodeGenPrep.
679 if (Subtarget->useCRBits())
680 setHasMultipleConditionRegisters();
682 setMinFunctionAlignment(2);
683 if (PPCSubTarget.isDarwin())
684 setPrefFunctionAlignment(4);
686 if (isPPC64 && Subtarget->isJITCodeModel())
687 // Temporary workaround for the inability of PPC64 JIT to handle jump
689 setSupportJumpTables(false);
691 setInsertFencesForAtomic(true);
693 if (Subtarget->enableMachineScheduler())
694 setSchedulingPreference(Sched::Source);
696 setSchedulingPreference(Sched::Hybrid);
698 computeRegisterProperties();
700 // The Freescale cores does better with aggressive inlining of memcpy and
701 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
702 if (Subtarget->getDarwinDirective() == PPC::DIR_E500mc ||
703 Subtarget->getDarwinDirective() == PPC::DIR_E5500) {
704 MaxStoresPerMemset = 32;
705 MaxStoresPerMemsetOptSize = 16;
706 MaxStoresPerMemcpy = 32;
707 MaxStoresPerMemcpyOptSize = 8;
708 MaxStoresPerMemmove = 32;
709 MaxStoresPerMemmoveOptSize = 8;
711 setPrefFunctionAlignment(4);
715 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
716 /// the desired ByVal argument alignment.
717 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
718 unsigned MaxMaxAlign) {
719 if (MaxAlign == MaxMaxAlign)
721 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
722 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
724 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
726 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
727 unsigned EltAlign = 0;
728 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
729 if (EltAlign > MaxAlign)
731 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
732 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
733 unsigned EltAlign = 0;
734 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
735 if (EltAlign > MaxAlign)
737 if (MaxAlign == MaxMaxAlign)
743 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
744 /// function arguments in the caller parameter area.
745 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
746 // Darwin passes everything on 4 byte boundary.
747 if (PPCSubTarget.isDarwin())
750 // 16byte and wider vectors are passed on 16byte boundary.
751 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
752 unsigned Align = PPCSubTarget.isPPC64() ? 8 : 4;
753 if (PPCSubTarget.hasAltivec() || PPCSubTarget.hasQPX())
754 getMaxByValAlign(Ty, Align, PPCSubTarget.hasQPX() ? 32 : 16);
758 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
760 default: return nullptr;
761 case PPCISD::FSEL: return "PPCISD::FSEL";
762 case PPCISD::FCFID: return "PPCISD::FCFID";
763 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
764 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
765 case PPCISD::FRE: return "PPCISD::FRE";
766 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
767 case PPCISD::STFIWX: return "PPCISD::STFIWX";
768 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
769 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
770 case PPCISD::VPERM: return "PPCISD::VPERM";
771 case PPCISD::Hi: return "PPCISD::Hi";
772 case PPCISD::Lo: return "PPCISD::Lo";
773 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
774 case PPCISD::TOC_RESTORE: return "PPCISD::TOC_RESTORE";
775 case PPCISD::LOAD: return "PPCISD::LOAD";
776 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
777 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
778 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
779 case PPCISD::SRL: return "PPCISD::SRL";
780 case PPCISD::SRA: return "PPCISD::SRA";
781 case PPCISD::SHL: return "PPCISD::SHL";
782 case PPCISD::CALL: return "PPCISD::CALL";
783 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
784 case PPCISD::MTCTR: return "PPCISD::MTCTR";
785 case PPCISD::BCTRL: return "PPCISD::BCTRL";
786 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
787 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
788 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
789 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
790 case PPCISD::VCMP: return "PPCISD::VCMP";
791 case PPCISD::VCMPo: return "PPCISD::VCMPo";
792 case PPCISD::LBRX: return "PPCISD::LBRX";
793 case PPCISD::STBRX: return "PPCISD::STBRX";
794 case PPCISD::LARX: return "PPCISD::LARX";
795 case PPCISD::STCX: return "PPCISD::STCX";
796 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
797 case PPCISD::BDNZ: return "PPCISD::BDNZ";
798 case PPCISD::BDZ: return "PPCISD::BDZ";
799 case PPCISD::MFFS: return "PPCISD::MFFS";
800 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
801 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
802 case PPCISD::CR6SET: return "PPCISD::CR6SET";
803 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
804 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
805 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
806 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
807 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
808 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
809 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
810 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
811 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
812 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
813 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
814 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
815 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
816 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
817 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
818 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
819 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
820 case PPCISD::SC: return "PPCISD::SC";
824 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
826 return PPCSubTarget.useCRBits() ? MVT::i1 : MVT::i32;
827 return VT.changeVectorElementTypeToInteger();
830 //===----------------------------------------------------------------------===//
831 // Node matching predicates, for use by the tblgen matching code.
832 //===----------------------------------------------------------------------===//
834 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
835 static bool isFloatingPointZero(SDValue Op) {
836 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
837 return CFP->getValueAPF().isZero();
838 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
839 // Maybe this has already been legalized into the constant pool?
840 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
841 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
842 return CFP->getValueAPF().isZero();
847 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
848 /// true if Op is undef or if it matches the specified value.
849 static bool isConstantOrUndef(int Op, int Val) {
850 return Op < 0 || Op == Val;
853 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
854 /// VPKUHUM instruction.
855 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
857 for (unsigned i = 0; i != 16; ++i)
858 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
861 for (unsigned i = 0; i != 8; ++i)
862 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) ||
863 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1))
869 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
870 /// VPKUWUM instruction.
871 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
873 for (unsigned i = 0; i != 16; i += 2)
874 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
875 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
878 for (unsigned i = 0; i != 8; i += 2)
879 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
880 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) ||
881 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) ||
882 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3))
888 /// isVMerge - Common function, used to match vmrg* shuffles.
890 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
891 unsigned LHSStart, unsigned RHSStart) {
892 if (N->getValueType(0) != MVT::v16i8)
894 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
895 "Unsupported merge size!");
897 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
898 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
899 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
900 LHSStart+j+i*UnitSize) ||
901 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
902 RHSStart+j+i*UnitSize))
908 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
909 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
910 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
913 return isVMerge(N, UnitSize, 8, 24);
914 return isVMerge(N, UnitSize, 8, 8);
917 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
918 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
919 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
922 return isVMerge(N, UnitSize, 0, 16);
923 return isVMerge(N, UnitSize, 0, 0);
927 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
928 /// amount, otherwise return -1.
929 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
930 if (N->getValueType(0) != MVT::v16i8)
933 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
935 // Find the first non-undef value in the shuffle mask.
937 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
940 if (i == 16) return -1; // all undef.
942 // Otherwise, check to see if the rest of the elements are consecutively
943 // numbered from this value.
944 unsigned ShiftAmt = SVOp->getMaskElt(i);
945 if (ShiftAmt < i) return -1;
949 // Check the rest of the elements to see if they are consecutive.
950 for (++i; i != 16; ++i)
951 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
954 // Check the rest of the elements to see if they are consecutive.
955 for (++i; i != 16; ++i)
956 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
962 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
963 /// specifies a splat of a single element that is suitable for input to
964 /// VSPLTB/VSPLTH/VSPLTW.
965 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
966 assert(N->getValueType(0) == MVT::v16i8 &&
967 (EltSize == 1 || EltSize == 2 || EltSize == 4));
969 // This is a splat operation if each element of the permute is the same, and
970 // if the value doesn't reference the second vector.
971 unsigned ElementBase = N->getMaskElt(0);
973 // FIXME: Handle UNDEF elements too!
974 if (ElementBase >= 16)
977 // Check that the indices are consecutive, in the case of a multi-byte element
978 // splatted with a v16i8 mask.
979 for (unsigned i = 1; i != EltSize; ++i)
980 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
983 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
984 if (N->getMaskElt(i) < 0) continue;
985 for (unsigned j = 0; j != EltSize; ++j)
986 if (N->getMaskElt(i+j) != N->getMaskElt(j))
992 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
994 bool PPC::isAllNegativeZeroVector(SDNode *N) {
995 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
997 APInt APVal, APUndef;
1001 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1002 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1003 return CFP->getValueAPF().isNegZero();
1008 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1009 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1010 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
1011 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1012 assert(isSplatShuffleMask(SVOp, EltSize));
1013 return SVOp->getMaskElt(0) / EltSize;
1016 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1017 /// by using a vspltis[bhw] instruction of the specified element size, return
1018 /// the constant being splatted. The ByteSize field indicates the number of
1019 /// bytes of each element [124] -> [bhw].
1020 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1021 SDValue OpVal(nullptr, 0);
1023 // If ByteSize of the splat is bigger than the element size of the
1024 // build_vector, then we have a case where we are checking for a splat where
1025 // multiple elements of the buildvector are folded together into a single
1026 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1027 unsigned EltSize = 16/N->getNumOperands();
1028 if (EltSize < ByteSize) {
1029 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1030 SDValue UniquedVals[4];
1031 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1033 // See if all of the elements in the buildvector agree across.
1034 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1035 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1036 // If the element isn't a constant, bail fully out.
1037 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1040 if (!UniquedVals[i&(Multiple-1)].getNode())
1041 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1042 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1043 return SDValue(); // no match.
1046 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1047 // either constant or undef values that are identical for each chunk. See
1048 // if these chunks can form into a larger vspltis*.
1050 // Check to see if all of the leading entries are either 0 or -1. If
1051 // neither, then this won't fit into the immediate field.
1052 bool LeadingZero = true;
1053 bool LeadingOnes = true;
1054 for (unsigned i = 0; i != Multiple-1; ++i) {
1055 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1057 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1058 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1060 // Finally, check the least significant entry.
1062 if (!UniquedVals[Multiple-1].getNode())
1063 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
1064 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1066 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
1069 if (!UniquedVals[Multiple-1].getNode())
1070 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
1071 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1072 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1073 return DAG.getTargetConstant(Val, MVT::i32);
1079 // Check to see if this buildvec has a single non-undef value in its elements.
1080 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1081 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1082 if (!OpVal.getNode())
1083 OpVal = N->getOperand(i);
1084 else if (OpVal != N->getOperand(i))
1088 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1090 unsigned ValSizeInBytes = EltSize;
1092 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1093 Value = CN->getZExtValue();
1094 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1095 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1096 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1099 // If the splat value is larger than the element value, then we can never do
1100 // this splat. The only case that we could fit the replicated bits into our
1101 // immediate field for would be zero, and we prefer to use vxor for it.
1102 if (ValSizeInBytes < ByteSize) return SDValue();
1104 // If the element value is larger than the splat value, cut it in half and
1105 // check to see if the two halves are equal. Continue doing this until we
1106 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
1107 while (ValSizeInBytes > ByteSize) {
1108 ValSizeInBytes >>= 1;
1110 // If the top half equals the bottom half, we're still ok.
1111 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1112 (Value & ((1 << (8*ValSizeInBytes))-1)))
1116 // Properly sign extend the value.
1117 int MaskVal = SignExtend32(Value, ByteSize * 8);
1119 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1120 if (MaskVal == 0) return SDValue();
1122 // Finally, if this value fits in a 5 bit sext field, return it
1123 if (SignExtend32<5>(MaskVal) == MaskVal)
1124 return DAG.getTargetConstant(MaskVal, MVT::i32);
1128 //===----------------------------------------------------------------------===//
1129 // Addressing Mode Selection
1130 //===----------------------------------------------------------------------===//
1132 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1133 /// or 64-bit immediate, and if the value can be accurately represented as a
1134 /// sign extension from a 16-bit value. If so, this returns true and the
1136 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1137 if (!isa<ConstantSDNode>(N))
1140 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1141 if (N->getValueType(0) == MVT::i32)
1142 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1144 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1146 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1147 return isIntS16Immediate(Op.getNode(), Imm);
1151 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1152 /// can be represented as an indexed [r+r] operation. Returns false if it
1153 /// can be more efficiently represented with [r+imm].
1154 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1156 SelectionDAG &DAG) const {
1158 if (N.getOpcode() == ISD::ADD) {
1159 if (isIntS16Immediate(N.getOperand(1), imm))
1160 return false; // r+i
1161 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1162 return false; // r+i
1164 Base = N.getOperand(0);
1165 Index = N.getOperand(1);
1167 } else if (N.getOpcode() == ISD::OR) {
1168 if (isIntS16Immediate(N.getOperand(1), imm))
1169 return false; // r+i can fold it if we can.
1171 // If this is an or of disjoint bitfields, we can codegen this as an add
1172 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1174 APInt LHSKnownZero, LHSKnownOne;
1175 APInt RHSKnownZero, RHSKnownOne;
1176 DAG.computeKnownBits(N.getOperand(0),
1177 LHSKnownZero, LHSKnownOne);
1179 if (LHSKnownZero.getBoolValue()) {
1180 DAG.computeKnownBits(N.getOperand(1),
1181 RHSKnownZero, RHSKnownOne);
1182 // If all of the bits are known zero on the LHS or RHS, the add won't
1184 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1185 Base = N.getOperand(0);
1186 Index = N.getOperand(1);
1195 // If we happen to be doing an i64 load or store into a stack slot that has
1196 // less than a 4-byte alignment, then the frame-index elimination may need to
1197 // use an indexed load or store instruction (because the offset may not be a
1198 // multiple of 4). The extra register needed to hold the offset comes from the
1199 // register scavenger, and it is possible that the scavenger will need to use
1200 // an emergency spill slot. As a result, we need to make sure that a spill slot
1201 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1203 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1204 // FIXME: This does not handle the LWA case.
1208 // NOTE: We'll exclude negative FIs here, which come from argument
1209 // lowering, because there are no known test cases triggering this problem
1210 // using packed structures (or similar). We can remove this exclusion if
1211 // we find such a test case. The reason why this is so test-case driven is
1212 // because this entire 'fixup' is only to prevent crashes (from the
1213 // register scavenger) on not-really-valid inputs. For example, if we have:
1215 // %b = bitcast i1* %a to i64*
1216 // store i64* a, i64 b
1217 // then the store should really be marked as 'align 1', but is not. If it
1218 // were marked as 'align 1' then the indexed form would have been
1219 // instruction-selected initially, and the problem this 'fixup' is preventing
1220 // won't happen regardless.
1224 MachineFunction &MF = DAG.getMachineFunction();
1225 MachineFrameInfo *MFI = MF.getFrameInfo();
1227 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1231 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1232 FuncInfo->setHasNonRISpills();
1235 /// Returns true if the address N can be represented by a base register plus
1236 /// a signed 16-bit displacement [r+imm], and if it is not better
1237 /// represented as reg+reg. If Aligned is true, only accept displacements
1238 /// suitable for STD and friends, i.e. multiples of 4.
1239 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1242 bool Aligned) const {
1243 // FIXME dl should come from parent load or store, not from address
1245 // If this can be more profitably realized as r+r, fail.
1246 if (SelectAddressRegReg(N, Disp, Base, DAG))
1249 if (N.getOpcode() == ISD::ADD) {
1251 if (isIntS16Immediate(N.getOperand(1), imm) &&
1252 (!Aligned || (imm & 3) == 0)) {
1253 Disp = DAG.getTargetConstant(imm, N.getValueType());
1254 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1255 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1256 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1258 Base = N.getOperand(0);
1260 return true; // [r+i]
1261 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1262 // Match LOAD (ADD (X, Lo(G))).
1263 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1264 && "Cannot handle constant offsets yet!");
1265 Disp = N.getOperand(1).getOperand(0); // The global address.
1266 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1267 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1268 Disp.getOpcode() == ISD::TargetConstantPool ||
1269 Disp.getOpcode() == ISD::TargetJumpTable);
1270 Base = N.getOperand(0);
1271 return true; // [&g+r]
1273 } else if (N.getOpcode() == ISD::OR) {
1275 if (isIntS16Immediate(N.getOperand(1), imm) &&
1276 (!Aligned || (imm & 3) == 0)) {
1277 // If this is an or of disjoint bitfields, we can codegen this as an add
1278 // (for better address arithmetic) if the LHS and RHS of the OR are
1279 // provably disjoint.
1280 APInt LHSKnownZero, LHSKnownOne;
1281 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1283 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1284 // If all of the bits are known zero on the LHS or RHS, the add won't
1286 Base = N.getOperand(0);
1287 Disp = DAG.getTargetConstant(imm, N.getValueType());
1291 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1292 // Loading from a constant address.
1294 // If this address fits entirely in a 16-bit sext immediate field, codegen
1297 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1298 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1299 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1300 CN->getValueType(0));
1304 // Handle 32-bit sext immediates with LIS + addr mode.
1305 if ((CN->getValueType(0) == MVT::i32 ||
1306 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1307 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1308 int Addr = (int)CN->getZExtValue();
1310 // Otherwise, break this down into an LIS + disp.
1311 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1313 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1314 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1315 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1320 Disp = DAG.getTargetConstant(0, getPointerTy());
1321 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1322 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1323 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1326 return true; // [r+0]
1329 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1330 /// represented as an indexed [r+r] operation.
1331 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1333 SelectionDAG &DAG) const {
1334 // Check to see if we can easily represent this as an [r+r] address. This
1335 // will fail if it thinks that the address is more profitably represented as
1336 // reg+imm, e.g. where imm = 0.
1337 if (SelectAddressRegReg(N, Base, Index, DAG))
1340 // If the operand is an addition, always emit this as [r+r], since this is
1341 // better (for code size, and execution, as the memop does the add for free)
1342 // than emitting an explicit add.
1343 if (N.getOpcode() == ISD::ADD) {
1344 Base = N.getOperand(0);
1345 Index = N.getOperand(1);
1349 // Otherwise, do it the hard way, using R0 as the base register.
1350 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1356 /// getPreIndexedAddressParts - returns true by value, base pointer and
1357 /// offset pointer and addressing mode by reference if the node's address
1358 /// can be legally represented as pre-indexed load / store address.
1359 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1361 ISD::MemIndexedMode &AM,
1362 SelectionDAG &DAG) const {
1363 if (DisablePPCPreinc) return false;
1369 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1370 Ptr = LD->getBasePtr();
1371 VT = LD->getMemoryVT();
1372 Alignment = LD->getAlignment();
1373 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1374 Ptr = ST->getBasePtr();
1375 VT = ST->getMemoryVT();
1376 Alignment = ST->getAlignment();
1381 // PowerPC doesn't have preinc load/store instructions for vectors.
1385 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1387 // Common code will reject creating a pre-inc form if the base pointer
1388 // is a frame index, or if N is a store and the base pointer is either
1389 // the same as or a predecessor of the value being stored. Check for
1390 // those situations here, and try with swapped Base/Offset instead.
1393 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1396 SDValue Val = cast<StoreSDNode>(N)->getValue();
1397 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1402 std::swap(Base, Offset);
1408 // LDU/STU can only handle immediates that are a multiple of 4.
1409 if (VT != MVT::i64) {
1410 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1413 // LDU/STU need an address with at least 4-byte alignment.
1417 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1421 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1422 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1423 // sext i32 to i64 when addr mode is r+i.
1424 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1425 LD->getExtensionType() == ISD::SEXTLOAD &&
1426 isa<ConstantSDNode>(Offset))
1434 //===----------------------------------------------------------------------===//
1435 // LowerOperation implementation
1436 //===----------------------------------------------------------------------===//
1438 /// GetLabelAccessInfo - Return true if we should reference labels using a
1439 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1440 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1441 unsigned &LoOpFlags,
1442 const GlobalValue *GV = nullptr) {
1443 HiOpFlags = PPCII::MO_HA;
1444 LoOpFlags = PPCII::MO_LO;
1446 // Don't use the pic base if not in PIC relocation model. Or if we are on a
1447 // non-darwin platform. We don't support PIC on other platforms yet.
1448 bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1449 TM.getSubtarget<PPCSubtarget>().isDarwin();
1451 HiOpFlags |= PPCII::MO_PIC_FLAG;
1452 LoOpFlags |= PPCII::MO_PIC_FLAG;
1455 // If this is a reference to a global value that requires a non-lazy-ptr, make
1456 // sure that instruction lowering adds it.
1457 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1458 HiOpFlags |= PPCII::MO_NLP_FLAG;
1459 LoOpFlags |= PPCII::MO_NLP_FLAG;
1461 if (GV->hasHiddenVisibility()) {
1462 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1463 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1470 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1471 SelectionDAG &DAG) {
1472 EVT PtrVT = HiPart.getValueType();
1473 SDValue Zero = DAG.getConstant(0, PtrVT);
1476 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1477 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1479 // With PIC, the first instruction is actually "GR+hi(&G)".
1481 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1482 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1484 // Generate non-pic code that has direct accesses to the constant pool.
1485 // The address of the global is just (hi(&g)+lo(&g)).
1486 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1489 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1490 SelectionDAG &DAG) const {
1491 EVT PtrVT = Op.getValueType();
1492 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1493 const Constant *C = CP->getConstVal();
1495 // 64-bit SVR4 ABI code is always position-independent.
1496 // The actual address of the GlobalValue is stored in the TOC.
1497 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1498 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1499 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1500 DAG.getRegister(PPC::X2, MVT::i64));
1503 unsigned MOHiFlag, MOLoFlag;
1504 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1506 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1508 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1509 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1512 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1513 EVT PtrVT = Op.getValueType();
1514 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1516 // 64-bit SVR4 ABI code is always position-independent.
1517 // The actual address of the GlobalValue is stored in the TOC.
1518 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1519 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1520 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1521 DAG.getRegister(PPC::X2, MVT::i64));
1524 unsigned MOHiFlag, MOLoFlag;
1525 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1526 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1527 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1528 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1531 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1532 SelectionDAG &DAG) const {
1533 EVT PtrVT = Op.getValueType();
1535 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1537 unsigned MOHiFlag, MOLoFlag;
1538 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1539 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1540 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1541 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1544 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1545 SelectionDAG &DAG) const {
1547 // FIXME: TLS addresses currently use medium model code sequences,
1548 // which is the most useful form. Eventually support for small and
1549 // large models could be added if users need it, at the cost of
1550 // additional complexity.
1551 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1553 const GlobalValue *GV = GA->getGlobal();
1554 EVT PtrVT = getPointerTy();
1555 bool is64bit = PPCSubTarget.isPPC64();
1557 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1559 if (Model == TLSModel::LocalExec) {
1560 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1561 PPCII::MO_TPREL_HA);
1562 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1563 PPCII::MO_TPREL_LO);
1564 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1565 is64bit ? MVT::i64 : MVT::i32);
1566 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1567 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1570 if (Model == TLSModel::InitialExec) {
1571 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1572 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1576 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1577 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1578 PtrVT, GOTReg, TGA);
1580 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1581 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1582 PtrVT, TGA, GOTPtr);
1583 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1586 if (Model == TLSModel::GeneralDynamic) {
1587 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1588 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1589 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1591 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1594 // We need a chain node, and don't have one handy. The underlying
1595 // call has no side effects, so using the function entry node
1597 SDValue Chain = DAG.getEntryNode();
1598 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1599 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1600 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1601 PtrVT, ParmReg, TGA);
1602 // The return value from GET_TLS_ADDR really is in X3 already, but
1603 // some hacks are needed here to tie everything together. The extra
1604 // copies dissolve during subsequent transforms.
1605 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1606 return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1609 if (Model == TLSModel::LocalDynamic) {
1610 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1611 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1612 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1614 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1617 // We need a chain node, and don't have one handy. The underlying
1618 // call has no side effects, so using the function entry node
1620 SDValue Chain = DAG.getEntryNode();
1621 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1622 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1623 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1624 PtrVT, ParmReg, TGA);
1625 // The return value from GET_TLSLD_ADDR really is in X3 already, but
1626 // some hacks are needed here to tie everything together. The extra
1627 // copies dissolve during subsequent transforms.
1628 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1629 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1630 Chain, ParmReg, TGA);
1631 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1634 llvm_unreachable("Unknown TLS model!");
1637 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1638 SelectionDAG &DAG) const {
1639 EVT PtrVT = Op.getValueType();
1640 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1642 const GlobalValue *GV = GSDN->getGlobal();
1644 // 64-bit SVR4 ABI code is always position-independent.
1645 // The actual address of the GlobalValue is stored in the TOC.
1646 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1647 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1648 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1649 DAG.getRegister(PPC::X2, MVT::i64));
1652 unsigned MOHiFlag, MOLoFlag;
1653 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1656 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1658 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1660 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1662 // If the global reference is actually to a non-lazy-pointer, we have to do an
1663 // extra load to get the address of the global.
1664 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1665 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1666 false, false, false, 0);
1670 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1671 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1674 if (Op.getValueType() == MVT::v2i64) {
1675 // When the operands themselves are v2i64 values, we need to do something
1676 // special because VSX has no underlying comparison operations for these.
1677 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1678 // Equality can be handled by casting to the legal type for Altivec
1679 // comparisons, everything else needs to be expanded.
1680 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1681 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1682 DAG.getSetCC(dl, MVT::v4i32,
1683 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1684 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1691 // We handle most of these in the usual way.
1695 // If we're comparing for equality to zero, expose the fact that this is
1696 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1697 // fold the new nodes.
1698 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1699 if (C->isNullValue() && CC == ISD::SETEQ) {
1700 EVT VT = Op.getOperand(0).getValueType();
1701 SDValue Zext = Op.getOperand(0);
1702 if (VT.bitsLT(MVT::i32)) {
1704 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1706 unsigned Log2b = Log2_32(VT.getSizeInBits());
1707 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1708 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1709 DAG.getConstant(Log2b, MVT::i32));
1710 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1712 // Leave comparisons against 0 and -1 alone for now, since they're usually
1713 // optimized. FIXME: revisit this when we can custom lower all setcc
1715 if (C->isAllOnesValue() || C->isNullValue())
1719 // If we have an integer seteq/setne, turn it into a compare against zero
1720 // by xor'ing the rhs with the lhs, which is faster than setting a
1721 // condition register, reading it back out, and masking the correct bit. The
1722 // normal approach here uses sub to do this instead of xor. Using xor exposes
1723 // the result to other bit-twiddling opportunities.
1724 EVT LHSVT = Op.getOperand(0).getValueType();
1725 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1726 EVT VT = Op.getValueType();
1727 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1729 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1734 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1735 const PPCSubtarget &Subtarget) const {
1736 SDNode *Node = Op.getNode();
1737 EVT VT = Node->getValueType(0);
1738 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1739 SDValue InChain = Node->getOperand(0);
1740 SDValue VAListPtr = Node->getOperand(1);
1741 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1744 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1747 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1748 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1750 InChain = GprIndex.getValue(1);
1752 if (VT == MVT::i64) {
1753 // Check if GprIndex is even
1754 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1755 DAG.getConstant(1, MVT::i32));
1756 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1757 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1758 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1759 DAG.getConstant(1, MVT::i32));
1760 // Align GprIndex to be even if it isn't
1761 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1765 // fpr index is 1 byte after gpr
1766 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1767 DAG.getConstant(1, MVT::i32));
1770 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1771 FprPtr, MachinePointerInfo(SV), MVT::i8,
1773 InChain = FprIndex.getValue(1);
1775 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1776 DAG.getConstant(8, MVT::i32));
1778 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1779 DAG.getConstant(4, MVT::i32));
1782 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1783 MachinePointerInfo(), false, false,
1785 InChain = OverflowArea.getValue(1);
1787 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1788 MachinePointerInfo(), false, false,
1790 InChain = RegSaveArea.getValue(1);
1792 // select overflow_area if index > 8
1793 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1794 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1796 // adjustment constant gpr_index * 4/8
1797 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1798 VT.isInteger() ? GprIndex : FprIndex,
1799 DAG.getConstant(VT.isInteger() ? 4 : 8,
1802 // OurReg = RegSaveArea + RegConstant
1803 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1806 // Floating types are 32 bytes into RegSaveArea
1807 if (VT.isFloatingPoint())
1808 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1809 DAG.getConstant(32, MVT::i32));
1811 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1812 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1813 VT.isInteger() ? GprIndex : FprIndex,
1814 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1817 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1818 VT.isInteger() ? VAListPtr : FprPtr,
1819 MachinePointerInfo(SV),
1820 MVT::i8, false, false, 0);
1822 // determine if we should load from reg_save_area or overflow_area
1823 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1825 // increase overflow_area by 4/8 if gpr/fpr > 8
1826 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1827 DAG.getConstant(VT.isInteger() ? 4 : 8,
1830 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1833 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1835 MachinePointerInfo(),
1836 MVT::i32, false, false, 0);
1838 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1839 false, false, false, 0);
1842 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
1843 const PPCSubtarget &Subtarget) const {
1844 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
1846 // We have to copy the entire va_list struct:
1847 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
1848 return DAG.getMemcpy(Op.getOperand(0), Op,
1849 Op.getOperand(1), Op.getOperand(2),
1850 DAG.getConstant(12, MVT::i32), 8, false, true,
1851 MachinePointerInfo(), MachinePointerInfo());
1854 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1855 SelectionDAG &DAG) const {
1856 return Op.getOperand(0);
1859 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1860 SelectionDAG &DAG) const {
1861 SDValue Chain = Op.getOperand(0);
1862 SDValue Trmp = Op.getOperand(1); // trampoline
1863 SDValue FPtr = Op.getOperand(2); // nested function
1864 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1867 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1868 bool isPPC64 = (PtrVT == MVT::i64);
1870 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1873 TargetLowering::ArgListTy Args;
1874 TargetLowering::ArgListEntry Entry;
1876 Entry.Ty = IntPtrTy;
1877 Entry.Node = Trmp; Args.push_back(Entry);
1879 // TrampSize == (isPPC64 ? 48 : 40);
1880 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1881 isPPC64 ? MVT::i64 : MVT::i32);
1882 Args.push_back(Entry);
1884 Entry.Node = FPtr; Args.push_back(Entry);
1885 Entry.Node = Nest; Args.push_back(Entry);
1887 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1888 TargetLowering::CallLoweringInfo CLI(DAG);
1889 CLI.setDebugLoc(dl).setChain(Chain)
1890 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
1891 DAG.getExternalSymbol("__trampoline_setup", PtrVT), &Args, 0);
1893 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1894 return CallResult.second;
1897 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1898 const PPCSubtarget &Subtarget) const {
1899 MachineFunction &MF = DAG.getMachineFunction();
1900 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1904 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1905 // vastart just stores the address of the VarArgsFrameIndex slot into the
1906 // memory location argument.
1907 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1908 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1909 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1910 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1911 MachinePointerInfo(SV),
1915 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1916 // We suppose the given va_list is already allocated.
1919 // char gpr; /* index into the array of 8 GPRs
1920 // * stored in the register save area
1921 // * gpr=0 corresponds to r3,
1922 // * gpr=1 to r4, etc.
1924 // char fpr; /* index into the array of 8 FPRs
1925 // * stored in the register save area
1926 // * fpr=0 corresponds to f1,
1927 // * fpr=1 to f2, etc.
1929 // char *overflow_arg_area;
1930 // /* location on stack that holds
1931 // * the next overflow argument
1933 // char *reg_save_area;
1934 // /* where r3:r10 and f1:f8 (if saved)
1940 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1941 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1944 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1946 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1948 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1951 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1952 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1954 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1955 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1957 uint64_t FPROffset = 1;
1958 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1960 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1962 // Store first byte : number of int regs
1963 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1965 MachinePointerInfo(SV),
1966 MVT::i8, false, false, 0);
1967 uint64_t nextOffset = FPROffset;
1968 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1971 // Store second byte : number of float regs
1972 SDValue secondStore =
1973 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1974 MachinePointerInfo(SV, nextOffset), MVT::i8,
1976 nextOffset += StackOffset;
1977 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1979 // Store second word : arguments given on stack
1980 SDValue thirdStore =
1981 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1982 MachinePointerInfo(SV, nextOffset),
1984 nextOffset += FrameOffset;
1985 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1987 // Store third word : arguments given in registers
1988 return DAG.getStore(thirdStore, dl, FR, nextPtr,
1989 MachinePointerInfo(SV, nextOffset),
1994 #include "PPCGenCallingConv.inc"
1996 // Function whose sole purpose is to kill compiler warnings
1997 // stemming from unused functions included from PPCGenCallingConv.inc.
1998 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
1999 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2002 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2003 CCValAssign::LocInfo &LocInfo,
2004 ISD::ArgFlagsTy &ArgFlags,
2009 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2011 CCValAssign::LocInfo &LocInfo,
2012 ISD::ArgFlagsTy &ArgFlags,
2014 static const MCPhysReg ArgRegs[] = {
2015 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2016 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2018 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2020 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2022 // Skip one register if the first unallocated register has an even register
2023 // number and there are still argument registers available which have not been
2024 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2025 // need to skip a register if RegNum is odd.
2026 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2027 State.AllocateReg(ArgRegs[RegNum]);
2030 // Always return false here, as this function only makes sure that the first
2031 // unallocated register has an odd register number and does not actually
2032 // allocate a register for the current argument.
2036 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2038 CCValAssign::LocInfo &LocInfo,
2039 ISD::ArgFlagsTy &ArgFlags,
2041 static const MCPhysReg ArgRegs[] = {
2042 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2046 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2048 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2050 // If there is only one Floating-point register left we need to put both f64
2051 // values of a split ppc_fp128 value on the stack.
2052 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2053 State.AllocateReg(ArgRegs[RegNum]);
2056 // Always return false here, as this function only makes sure that the two f64
2057 // values a ppc_fp128 value is split into are both passed in registers or both
2058 // passed on the stack and does not actually allocate a register for the
2059 // current argument.
2063 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2065 static const MCPhysReg *GetFPR() {
2066 static const MCPhysReg FPR[] = {
2067 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2068 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2074 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2076 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2077 unsigned PtrByteSize) {
2078 unsigned ArgSize = ArgVT.getStoreSize();
2079 if (Flags.isByVal())
2080 ArgSize = Flags.getByValSize();
2081 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2087 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2088 CallingConv::ID CallConv, bool isVarArg,
2089 const SmallVectorImpl<ISD::InputArg>
2091 SDLoc dl, SelectionDAG &DAG,
2092 SmallVectorImpl<SDValue> &InVals)
2094 if (PPCSubTarget.isSVR4ABI()) {
2095 if (PPCSubTarget.isPPC64())
2096 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2099 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2102 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2108 PPCTargetLowering::LowerFormalArguments_32SVR4(
2110 CallingConv::ID CallConv, bool isVarArg,
2111 const SmallVectorImpl<ISD::InputArg>
2113 SDLoc dl, SelectionDAG &DAG,
2114 SmallVectorImpl<SDValue> &InVals) const {
2116 // 32-bit SVR4 ABI Stack Frame Layout:
2117 // +-----------------------------------+
2118 // +--> | Back chain |
2119 // | +-----------------------------------+
2120 // | | Floating-point register save area |
2121 // | +-----------------------------------+
2122 // | | General register save area |
2123 // | +-----------------------------------+
2124 // | | CR save word |
2125 // | +-----------------------------------+
2126 // | | VRSAVE save word |
2127 // | +-----------------------------------+
2128 // | | Alignment padding |
2129 // | +-----------------------------------+
2130 // | | Vector register save area |
2131 // | +-----------------------------------+
2132 // | | Local variable space |
2133 // | +-----------------------------------+
2134 // | | Parameter list area |
2135 // | +-----------------------------------+
2136 // | | LR save word |
2137 // | +-----------------------------------+
2138 // SP--> +--- | Back chain |
2139 // +-----------------------------------+
2142 // System V Application Binary Interface PowerPC Processor Supplement
2143 // AltiVec Technology Programming Interface Manual
2145 MachineFunction &MF = DAG.getMachineFunction();
2146 MachineFrameInfo *MFI = MF.getFrameInfo();
2147 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2149 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2150 // Potential tail calls could cause overwriting of argument stack slots.
2151 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2152 (CallConv == CallingConv::Fast));
2153 unsigned PtrByteSize = 4;
2155 // Assign locations to all of the incoming arguments.
2156 SmallVector<CCValAssign, 16> ArgLocs;
2157 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2158 getTargetMachine(), ArgLocs, *DAG.getContext());
2160 // Reserve space for the linkage area on the stack.
2161 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
2163 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2165 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2166 CCValAssign &VA = ArgLocs[i];
2168 // Arguments stored in registers.
2169 if (VA.isRegLoc()) {
2170 const TargetRegisterClass *RC;
2171 EVT ValVT = VA.getValVT();
2173 switch (ValVT.getSimpleVT().SimpleTy) {
2175 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2178 RC = &PPC::GPRCRegClass;
2181 RC = &PPC::F4RCRegClass;
2184 if (PPCSubTarget.hasVSX())
2185 RC = &PPC::VSFRCRegClass;
2187 RC = &PPC::F8RCRegClass;
2193 RC = &PPC::VRRCRegClass;
2197 RC = &PPC::VSHRCRegClass;
2201 // Transform the arguments stored in physical registers into virtual ones.
2202 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2203 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2204 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2206 if (ValVT == MVT::i1)
2207 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2209 InVals.push_back(ArgValue);
2211 // Argument stored in memory.
2212 assert(VA.isMemLoc());
2214 unsigned ArgSize = VA.getLocVT().getStoreSize();
2215 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2218 // Create load nodes to retrieve arguments from the stack.
2219 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2220 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2221 MachinePointerInfo(),
2222 false, false, false, 0));
2226 // Assign locations to all of the incoming aggregate by value arguments.
2227 // Aggregates passed by value are stored in the local variable space of the
2228 // caller's stack frame, right above the parameter list area.
2229 SmallVector<CCValAssign, 16> ByValArgLocs;
2230 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2231 getTargetMachine(), ByValArgLocs, *DAG.getContext());
2233 // Reserve stack space for the allocations in CCInfo.
2234 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2236 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2238 // Area that is at least reserved in the caller of this function.
2239 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2241 // Set the size that is at least reserved in caller of this function. Tail
2242 // call optimized function's reserved stack space needs to be aligned so that
2243 // taking the difference between two stack areas will result in an aligned
2245 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2248 std::max(MinReservedArea,
2249 PPCFrameLowering::getMinCallFrameSize(false, false));
2251 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
2252 getStackAlignment();
2253 unsigned AlignMask = TargetAlign-1;
2254 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2256 FI->setMinReservedArea(MinReservedArea);
2258 SmallVector<SDValue, 8> MemOps;
2260 // If the function takes variable number of arguments, make a frame index for
2261 // the start of the first vararg value... for expansion of llvm.va_start.
2263 static const MCPhysReg GPArgRegs[] = {
2264 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2265 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2267 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2269 static const MCPhysReg FPArgRegs[] = {
2270 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2273 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2275 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2277 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2280 // Make room for NumGPArgRegs and NumFPArgRegs.
2281 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2282 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2284 FuncInfo->setVarArgsStackOffset(
2285 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2286 CCInfo.getNextStackOffset(), true));
2288 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2289 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2291 // The fixed integer arguments of a variadic function are stored to the
2292 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2293 // the result of va_next.
2294 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2295 // Get an existing live-in vreg, or add a new one.
2296 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2298 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2300 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2301 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2302 MachinePointerInfo(), false, false, 0);
2303 MemOps.push_back(Store);
2304 // Increment the address by four for the next argument to store
2305 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2306 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2309 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2311 // The double arguments are stored to the VarArgsFrameIndex
2313 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2314 // Get an existing live-in vreg, or add a new one.
2315 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2317 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2319 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2320 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2321 MachinePointerInfo(), false, false, 0);
2322 MemOps.push_back(Store);
2323 // Increment the address by eight for the next argument to store
2324 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2326 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2330 if (!MemOps.empty())
2331 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2336 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2337 // value to MVT::i64 and then truncate to the correct register size.
2339 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2340 SelectionDAG &DAG, SDValue ArgVal,
2343 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2344 DAG.getValueType(ObjectVT));
2345 else if (Flags.isZExt())
2346 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2347 DAG.getValueType(ObjectVT));
2349 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2352 // Set the size that is at least reserved in caller of this function. Tail
2353 // call optimized functions' reserved stack space needs to be aligned so that
2354 // taking the difference between two stack areas will result in an aligned
2357 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG,
2358 unsigned nAltivecParamsAtEnd,
2359 unsigned MinReservedArea,
2360 bool isPPC64) const {
2361 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2362 // Add the Altivec parameters at the end, if needed.
2363 if (nAltivecParamsAtEnd) {
2364 MinReservedArea = ((MinReservedArea+15)/16)*16;
2365 MinReservedArea += 16*nAltivecParamsAtEnd;
2368 std::max(MinReservedArea,
2369 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2370 unsigned TargetAlign
2371 = DAG.getMachineFunction().getTarget().getFrameLowering()->
2372 getStackAlignment();
2373 unsigned AlignMask = TargetAlign-1;
2374 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2375 FI->setMinReservedArea(MinReservedArea);
2379 PPCTargetLowering::LowerFormalArguments_64SVR4(
2381 CallingConv::ID CallConv, bool isVarArg,
2382 const SmallVectorImpl<ISD::InputArg>
2384 SDLoc dl, SelectionDAG &DAG,
2385 SmallVectorImpl<SDValue> &InVals) const {
2386 // TODO: add description of PPC stack frame format, or at least some docs.
2388 MachineFunction &MF = DAG.getMachineFunction();
2389 MachineFrameInfo *MFI = MF.getFrameInfo();
2390 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2392 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2393 // Potential tail calls could cause overwriting of argument stack slots.
2394 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2395 (CallConv == CallingConv::Fast));
2396 unsigned PtrByteSize = 8;
2398 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
2399 // Area that is at least reserved in caller of this function.
2400 unsigned MinReservedArea = ArgOffset;
2402 static const MCPhysReg GPR[] = {
2403 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2404 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2407 static const MCPhysReg *FPR = GetFPR();
2409 static const MCPhysReg VR[] = {
2410 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2411 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2413 static const MCPhysReg VSRH[] = {
2414 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2415 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2418 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2419 const unsigned Num_FPR_Regs = 13;
2420 const unsigned Num_VR_Regs = array_lengthof(VR);
2422 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2424 // Add DAG nodes to load the arguments or copy them out of registers. On
2425 // entry to a function on PPC, the arguments start after the linkage area,
2426 // although the first ones are often in registers.
2428 SmallVector<SDValue, 8> MemOps;
2429 unsigned nAltivecParamsAtEnd = 0;
2430 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2431 unsigned CurArgIdx = 0;
2432 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2434 bool needsLoad = false;
2435 EVT ObjectVT = Ins[ArgNo].VT;
2436 unsigned ObjSize = ObjectVT.getStoreSize();
2437 unsigned ArgSize = ObjSize;
2438 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2439 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2440 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2442 unsigned CurArgOffset = ArgOffset;
2444 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2445 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2446 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8 ||
2447 ObjectVT==MVT::v2f64 || ObjectVT==MVT::v2i64) {
2449 MinReservedArea = ((MinReservedArea+15)/16)*16;
2450 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2454 nAltivecParamsAtEnd++;
2456 // Calculate min reserved area.
2457 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2461 // FIXME the codegen can be much improved in some cases.
2462 // We do not have to keep everything in memory.
2463 if (Flags.isByVal()) {
2464 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2465 ObjSize = Flags.getByValSize();
2466 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2467 // Empty aggregate parameters do not take up registers. Examples:
2471 // etc. However, we have to provide a place-holder in InVals, so
2472 // pretend we have an 8-byte item at the current address for that
2475 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2476 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2477 InVals.push_back(FIN);
2481 unsigned BVAlign = Flags.getByValAlign();
2483 ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
2484 CurArgOffset = ArgOffset;
2487 // All aggregates smaller than 8 bytes must be passed right-justified.
2488 if (ObjSize < PtrByteSize)
2489 CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize);
2490 // The value of the object is its address.
2491 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2492 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2493 InVals.push_back(FIN);
2496 if (GPR_idx != Num_GPR_Regs) {
2497 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2498 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2501 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2502 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2503 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2504 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2505 MachinePointerInfo(FuncArg),
2506 ObjType, false, false, 0);
2508 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2509 // store the whole register as-is to the parameter save area
2510 // slot. The address of the parameter was already calculated
2511 // above (InVals.push_back(FIN)) to be the right-justified
2512 // offset within the slot. For this store, we need a new
2513 // frame index that points at the beginning of the slot.
2514 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2515 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2516 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2517 MachinePointerInfo(FuncArg),
2521 MemOps.push_back(Store);
2524 // Whether we copied from a register or not, advance the offset
2525 // into the parameter save area by a full doubleword.
2526 ArgOffset += PtrByteSize;
2530 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2531 // Store whatever pieces of the object are in registers
2532 // to memory. ArgOffset will be the address of the beginning
2534 if (GPR_idx != Num_GPR_Regs) {
2536 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2537 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2538 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2539 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2540 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2541 MachinePointerInfo(FuncArg, j),
2543 MemOps.push_back(Store);
2545 ArgOffset += PtrByteSize;
2547 ArgOffset += ArgSize - j;
2554 switch (ObjectVT.getSimpleVT().SimpleTy) {
2555 default: llvm_unreachable("Unhandled argument type!");
2559 if (GPR_idx != Num_GPR_Regs) {
2560 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2561 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2563 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2564 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2565 // value to MVT::i64 and then truncate to the correct register size.
2566 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2571 ArgSize = PtrByteSize;
2578 // Every 8 bytes of argument space consumes one of the GPRs available for
2579 // argument passing.
2580 if (GPR_idx != Num_GPR_Regs) {
2583 if (FPR_idx != Num_FPR_Regs) {
2586 if (ObjectVT == MVT::f32)
2587 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2589 VReg = MF.addLiveIn(FPR[FPR_idx], PPCSubTarget.hasVSX() ?
2590 &PPC::VSFRCRegClass :
2591 &PPC::F8RCRegClass);
2593 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2597 ArgSize = PtrByteSize;
2608 // Note that vector arguments in registers don't reserve stack space,
2609 // except in varargs functions.
2610 if (VR_idx != Num_VR_Regs) {
2611 unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2612 MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2613 MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2614 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2616 while ((ArgOffset % 16) != 0) {
2617 ArgOffset += PtrByteSize;
2618 if (GPR_idx != Num_GPR_Regs)
2622 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2626 // Vectors are aligned.
2627 ArgOffset = ((ArgOffset+15)/16)*16;
2628 CurArgOffset = ArgOffset;
2635 // We need to load the argument to a virtual register if we determined
2636 // above that we ran out of physical registers of the appropriate type.
2638 int FI = MFI->CreateFixedObject(ObjSize,
2639 CurArgOffset + (ArgSize - ObjSize),
2641 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2642 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2643 false, false, false, 0);
2646 InVals.push_back(ArgVal);
2649 // Set the size that is at least reserved in caller of this function. Tail
2650 // call optimized functions' reserved stack space needs to be aligned so that
2651 // taking the difference between two stack areas will result in an aligned
2653 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true);
2655 // If the function takes variable number of arguments, make a frame index for
2656 // the start of the first vararg value... for expansion of llvm.va_start.
2658 int Depth = ArgOffset;
2660 FuncInfo->setVarArgsFrameIndex(
2661 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2662 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2664 // If this function is vararg, store any remaining integer argument regs
2665 // to their spots on the stack so that they may be loaded by deferencing the
2666 // result of va_next.
2667 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2668 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2669 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2670 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2671 MachinePointerInfo(), false, false, 0);
2672 MemOps.push_back(Store);
2673 // Increment the address by four for the next argument to store
2674 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2675 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2679 if (!MemOps.empty())
2680 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2686 PPCTargetLowering::LowerFormalArguments_Darwin(
2688 CallingConv::ID CallConv, bool isVarArg,
2689 const SmallVectorImpl<ISD::InputArg>
2691 SDLoc dl, SelectionDAG &DAG,
2692 SmallVectorImpl<SDValue> &InVals) const {
2693 // TODO: add description of PPC stack frame format, or at least some docs.
2695 MachineFunction &MF = DAG.getMachineFunction();
2696 MachineFrameInfo *MFI = MF.getFrameInfo();
2697 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2699 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2700 bool isPPC64 = PtrVT == MVT::i64;
2701 // Potential tail calls could cause overwriting of argument stack slots.
2702 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2703 (CallConv == CallingConv::Fast));
2704 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2706 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
2707 // Area that is at least reserved in caller of this function.
2708 unsigned MinReservedArea = ArgOffset;
2710 static const MCPhysReg GPR_32[] = { // 32-bit registers.
2711 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2712 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2714 static const MCPhysReg GPR_64[] = { // 64-bit registers.
2715 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2716 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2719 static const MCPhysReg *FPR = GetFPR();
2721 static const MCPhysReg VR[] = {
2722 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2723 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2726 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2727 const unsigned Num_FPR_Regs = 13;
2728 const unsigned Num_VR_Regs = array_lengthof( VR);
2730 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2732 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
2734 // In 32-bit non-varargs functions, the stack space for vectors is after the
2735 // stack space for non-vectors. We do not use this space unless we have
2736 // too many vectors to fit in registers, something that only occurs in
2737 // constructed examples:), but we have to walk the arglist to figure
2738 // that out...for the pathological case, compute VecArgOffset as the
2739 // start of the vector parameter area. Computing VecArgOffset is the
2740 // entire point of the following loop.
2741 unsigned VecArgOffset = ArgOffset;
2742 if (!isVarArg && !isPPC64) {
2743 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2745 EVT ObjectVT = Ins[ArgNo].VT;
2746 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2748 if (Flags.isByVal()) {
2749 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2750 unsigned ObjSize = Flags.getByValSize();
2752 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2753 VecArgOffset += ArgSize;
2757 switch(ObjectVT.getSimpleVT().SimpleTy) {
2758 default: llvm_unreachable("Unhandled argument type!");
2764 case MVT::i64: // PPC64
2766 // FIXME: We are guaranteed to be !isPPC64 at this point.
2767 // Does MVT::i64 apply?
2774 // Nothing to do, we're only looking at Nonvector args here.
2779 // We've found where the vector parameter area in memory is. Skip the
2780 // first 12 parameters; these don't use that memory.
2781 VecArgOffset = ((VecArgOffset+15)/16)*16;
2782 VecArgOffset += 12*16;
2784 // Add DAG nodes to load the arguments or copy them out of registers. On
2785 // entry to a function on PPC, the arguments start after the linkage area,
2786 // although the first ones are often in registers.
2788 SmallVector<SDValue, 8> MemOps;
2789 unsigned nAltivecParamsAtEnd = 0;
2790 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2791 unsigned CurArgIdx = 0;
2792 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2794 bool needsLoad = false;
2795 EVT ObjectVT = Ins[ArgNo].VT;
2796 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2797 unsigned ArgSize = ObjSize;
2798 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2799 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2800 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2802 unsigned CurArgOffset = ArgOffset;
2804 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2805 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2806 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2807 if (isVarArg || isPPC64) {
2808 MinReservedArea = ((MinReservedArea+15)/16)*16;
2809 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2812 } else nAltivecParamsAtEnd++;
2814 // Calculate min reserved area.
2815 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2819 // FIXME the codegen can be much improved in some cases.
2820 // We do not have to keep everything in memory.
2821 if (Flags.isByVal()) {
2822 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2823 ObjSize = Flags.getByValSize();
2824 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2825 // Objects of size 1 and 2 are right justified, everything else is
2826 // left justified. This means the memory address is adjusted forwards.
2827 if (ObjSize==1 || ObjSize==2) {
2828 CurArgOffset = CurArgOffset + (4 - ObjSize);
2830 // The value of the object is its address.
2831 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2832 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2833 InVals.push_back(FIN);
2834 if (ObjSize==1 || ObjSize==2) {
2835 if (GPR_idx != Num_GPR_Regs) {
2838 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2840 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2841 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2842 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2843 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2844 MachinePointerInfo(FuncArg),
2845 ObjType, false, false, 0);
2846 MemOps.push_back(Store);
2850 ArgOffset += PtrByteSize;
2854 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2855 // Store whatever pieces of the object are in registers
2856 // to memory. ArgOffset will be the address of the beginning
2858 if (GPR_idx != Num_GPR_Regs) {
2861 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2863 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2864 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2865 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2866 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2867 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2868 MachinePointerInfo(FuncArg, j),
2870 MemOps.push_back(Store);
2872 ArgOffset += PtrByteSize;
2874 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2881 switch (ObjectVT.getSimpleVT().SimpleTy) {
2882 default: llvm_unreachable("Unhandled argument type!");
2886 if (GPR_idx != Num_GPR_Regs) {
2887 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2888 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2890 if (ObjectVT == MVT::i1)
2891 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
2896 ArgSize = PtrByteSize;
2898 // All int arguments reserve stack space in the Darwin ABI.
2899 ArgOffset += PtrByteSize;
2903 case MVT::i64: // PPC64
2904 if (GPR_idx != Num_GPR_Regs) {
2905 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2906 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2908 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2909 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2910 // value to MVT::i64 and then truncate to the correct register size.
2911 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2916 ArgSize = PtrByteSize;
2918 // All int arguments reserve stack space in the Darwin ABI.
2924 // Every 4 bytes of argument space consumes one of the GPRs available for
2925 // argument passing.
2926 if (GPR_idx != Num_GPR_Regs) {
2928 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2931 if (FPR_idx != Num_FPR_Regs) {
2934 if (ObjectVT == MVT::f32)
2935 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2937 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2939 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2945 // All FP arguments reserve stack space in the Darwin ABI.
2946 ArgOffset += isPPC64 ? 8 : ObjSize;
2952 // Note that vector arguments in registers don't reserve stack space,
2953 // except in varargs functions.
2954 if (VR_idx != Num_VR_Regs) {
2955 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2956 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2958 while ((ArgOffset % 16) != 0) {
2959 ArgOffset += PtrByteSize;
2960 if (GPR_idx != Num_GPR_Regs)
2964 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2968 if (!isVarArg && !isPPC64) {
2969 // Vectors go after all the nonvectors.
2970 CurArgOffset = VecArgOffset;
2973 // Vectors are aligned.
2974 ArgOffset = ((ArgOffset+15)/16)*16;
2975 CurArgOffset = ArgOffset;
2983 // We need to load the argument to a virtual register if we determined above
2984 // that we ran out of physical registers of the appropriate type.
2986 int FI = MFI->CreateFixedObject(ObjSize,
2987 CurArgOffset + (ArgSize - ObjSize),
2989 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2990 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2991 false, false, false, 0);
2994 InVals.push_back(ArgVal);
2997 // Set the size that is at least reserved in caller of this function. Tail
2998 // call optimized functions' reserved stack space needs to be aligned so that
2999 // taking the difference between two stack areas will result in an aligned
3001 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64);
3003 // If the function takes variable number of arguments, make a frame index for
3004 // the start of the first vararg value... for expansion of llvm.va_start.
3006 int Depth = ArgOffset;
3008 FuncInfo->setVarArgsFrameIndex(
3009 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3011 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3013 // If this function is vararg, store any remaining integer argument regs
3014 // to their spots on the stack so that they may be loaded by deferencing the
3015 // result of va_next.
3016 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3020 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3022 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3024 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3025 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3026 MachinePointerInfo(), false, false, 0);
3027 MemOps.push_back(Store);
3028 // Increment the address by four for the next argument to store
3029 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3030 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3034 if (!MemOps.empty())
3035 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3040 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus
3041 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI.
3043 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
3047 const SmallVectorImpl<ISD::OutputArg>
3049 const SmallVectorImpl<SDValue> &OutVals,
3050 unsigned &nAltivecParamsAtEnd) {
3051 // Count how many bytes are to be pushed on the stack, including the linkage
3052 // area, and parameter passing area. We start with 24/48 bytes, which is
3053 // prereserved space for [SP][CR][LR][3 x unused].
3054 unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
3055 unsigned NumOps = Outs.size();
3056 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3058 // Add up all the space actually used.
3059 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
3060 // they all go in registers, but we must reserve stack space for them for
3061 // possible use by the caller. In varargs or 64-bit calls, parameters are
3062 // assigned stack space in order, with padding so Altivec parameters are
3064 nAltivecParamsAtEnd = 0;
3065 for (unsigned i = 0; i != NumOps; ++i) {
3066 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3067 EVT ArgVT = Outs[i].VT;
3068 // Varargs Altivec parameters are padded to a 16 byte boundary.
3069 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
3070 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8 ||
3071 ArgVT==MVT::v2f64 || ArgVT==MVT::v2i64) {
3072 if (!isVarArg && !isPPC64) {
3073 // Non-varargs Altivec parameters go after all the non-Altivec
3074 // parameters; handle those later so we know how much padding we need.
3075 nAltivecParamsAtEnd++;
3078 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
3079 NumBytes = ((NumBytes+15)/16)*16;
3081 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3084 // Allow for Altivec parameters at the end, if needed.
3085 if (nAltivecParamsAtEnd) {
3086 NumBytes = ((NumBytes+15)/16)*16;
3087 NumBytes += 16*nAltivecParamsAtEnd;
3090 // The prolog code of the callee may store up to 8 GPR argument registers to
3091 // the stack, allowing va_start to index over them in memory if its varargs.
3092 // Because we cannot tell if this is needed on the caller side, we have to
3093 // conservatively assume that it is needed. As such, make sure we have at
3094 // least enough stack space for the caller to store the 8 GPRs.
3095 NumBytes = std::max(NumBytes,
3096 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
3098 // Tail call needs the stack to be aligned.
3099 if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
3100 unsigned TargetAlign = DAG.getMachineFunction().getTarget().
3101 getFrameLowering()->getStackAlignment();
3102 unsigned AlignMask = TargetAlign-1;
3103 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3109 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3110 /// adjusted to accommodate the arguments for the tailcall.
3111 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3112 unsigned ParamSize) {
3114 if (!isTailCall) return 0;
3116 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3117 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3118 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3119 // Remember only if the new adjustement is bigger.
3120 if (SPDiff < FI->getTailCallSPDelta())
3121 FI->setTailCallSPDelta(SPDiff);
3126 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3127 /// for tail call optimization. Targets which want to do tail call
3128 /// optimization should implement this function.
3130 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3131 CallingConv::ID CalleeCC,
3133 const SmallVectorImpl<ISD::InputArg> &Ins,
3134 SelectionDAG& DAG) const {
3135 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3138 // Variable argument functions are not supported.
3142 MachineFunction &MF = DAG.getMachineFunction();
3143 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3144 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3145 // Functions containing by val parameters are not supported.
3146 for (unsigned i = 0; i != Ins.size(); i++) {
3147 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3148 if (Flags.isByVal()) return false;
3151 // Non-PIC/GOT tail calls are supported.
3152 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3155 // At the moment we can only do local tail calls (in same module, hidden
3156 // or protected) if we are generating PIC.
3157 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3158 return G->getGlobal()->hasHiddenVisibility()
3159 || G->getGlobal()->hasProtectedVisibility();
3165 /// isCallCompatibleAddress - Return the immediate to use if the specified
3166 /// 32-bit value is representable in the immediate field of a BxA instruction.
3167 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3168 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3169 if (!C) return nullptr;
3171 int Addr = C->getZExtValue();
3172 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3173 SignExtend32<26>(Addr) != Addr)
3174 return nullptr; // Top 6 bits have to be sext of immediate.
3176 return DAG.getConstant((int)C->getZExtValue() >> 2,
3177 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3182 struct TailCallArgumentInfo {
3187 TailCallArgumentInfo() : FrameIdx(0) {}
3192 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3194 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3196 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3197 SmallVectorImpl<SDValue> &MemOpChains,
3199 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3200 SDValue Arg = TailCallArgs[i].Arg;
3201 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3202 int FI = TailCallArgs[i].FrameIdx;
3203 // Store relative to framepointer.
3204 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3205 MachinePointerInfo::getFixedStack(FI),
3210 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3211 /// the appropriate stack slot for the tail call optimized function call.
3212 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3213 MachineFunction &MF,
3222 // Calculate the new stack slot for the return address.
3223 int SlotSize = isPPC64 ? 8 : 4;
3224 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3226 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3227 NewRetAddrLoc, true);
3228 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3229 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3230 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3231 MachinePointerInfo::getFixedStack(NewRetAddr),
3234 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3235 // slot as the FP is never overwritten.
3238 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3239 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3241 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3242 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3243 MachinePointerInfo::getFixedStack(NewFPIdx),
3250 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3251 /// the position of the argument.
3253 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3254 SDValue Arg, int SPDiff, unsigned ArgOffset,
3255 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3256 int Offset = ArgOffset + SPDiff;
3257 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3258 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3259 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3260 SDValue FIN = DAG.getFrameIndex(FI, VT);
3261 TailCallArgumentInfo Info;
3263 Info.FrameIdxOp = FIN;
3265 TailCallArguments.push_back(Info);
3268 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3269 /// stack slot. Returns the chain as result and the loaded frame pointers in
3270 /// LROpOut/FPOpout. Used when tail calling.
3271 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3279 // Load the LR and FP stack slot for later adjusting.
3280 EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
3281 LROpOut = getReturnAddrFrameIndex(DAG);
3282 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3283 false, false, false, 0);
3284 Chain = SDValue(LROpOut.getNode(), 1);
3286 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3287 // slot as the FP is never overwritten.
3289 FPOpOut = getFramePointerFrameIndex(DAG);
3290 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3291 false, false, false, 0);
3292 Chain = SDValue(FPOpOut.getNode(), 1);
3298 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3299 /// by "Src" to address "Dst" of size "Size". Alignment information is
3300 /// specified by the specific parameter attribute. The copy will be passed as
3301 /// a byval function parameter.
3302 /// Sometimes what we are copying is the end of a larger object, the part that
3303 /// does not fit in registers.
3305 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3306 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3308 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3309 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3310 false, false, MachinePointerInfo(),
3311 MachinePointerInfo());
3314 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3317 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3318 SDValue Arg, SDValue PtrOff, int SPDiff,
3319 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3320 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3321 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3323 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3328 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3330 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3331 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3332 DAG.getConstant(ArgOffset, PtrVT));
3334 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3335 MachinePointerInfo(), false, false, 0));
3336 // Calculate and remember argument location.
3337 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3342 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3343 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3344 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3345 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3346 MachineFunction &MF = DAG.getMachineFunction();
3348 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3349 // might overwrite each other in case of tail call optimization.
3350 SmallVector<SDValue, 8> MemOpChains2;
3351 // Do not flag preceding copytoreg stuff together with the following stuff.
3353 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3355 if (!MemOpChains2.empty())
3356 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3358 // Store the return address to the appropriate stack slot.
3359 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3360 isPPC64, isDarwinABI, dl);
3362 // Emit callseq_end just before tailcall node.
3363 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3364 DAG.getIntPtrConstant(0, true), InFlag, dl);
3365 InFlag = Chain.getValue(1);
3369 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3370 SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3371 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3372 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3373 const PPCSubtarget &PPCSubTarget) {
3375 bool isPPC64 = PPCSubTarget.isPPC64();
3376 bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
3378 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3379 NodeTys.push_back(MVT::Other); // Returns a chain
3380 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3382 unsigned CallOpc = PPCISD::CALL;
3384 bool needIndirectCall = true;
3385 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3386 // If this is an absolute destination address, use the munged value.
3387 Callee = SDValue(Dest, 0);
3388 needIndirectCall = false;
3391 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3392 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3393 // Use indirect calls for ALL functions calls in JIT mode, since the
3394 // far-call stubs may be outside relocation limits for a BL instruction.
3395 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3396 unsigned OpFlags = 0;
3397 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3398 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3399 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3400 (G->getGlobal()->isDeclaration() ||
3401 G->getGlobal()->isWeakForLinker())) {
3402 // PC-relative references to external symbols should go through $stub,
3403 // unless we're building with the leopard linker or later, which
3404 // automatically synthesizes these stubs.
3405 OpFlags = PPCII::MO_DARWIN_STUB;
3408 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3409 // every direct call is) turn it into a TargetGlobalAddress /
3410 // TargetExternalSymbol node so that legalize doesn't hack it.
3411 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3412 Callee.getValueType(),
3414 needIndirectCall = false;
3418 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3419 unsigned char OpFlags = 0;
3421 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3422 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3423 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
3424 // PC-relative references to external symbols should go through $stub,
3425 // unless we're building with the leopard linker or later, which
3426 // automatically synthesizes these stubs.
3427 OpFlags = PPCII::MO_DARWIN_STUB;
3430 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3432 needIndirectCall = false;
3435 if (needIndirectCall) {
3436 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3437 // to do the call, we can't use PPCISD::CALL.
3438 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3440 if (isSVR4ABI && isPPC64) {
3441 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3442 // entry point, but to the function descriptor (the function entry point
3443 // address is part of the function descriptor though).
3444 // The function descriptor is a three doubleword structure with the
3445 // following fields: function entry point, TOC base address and
3446 // environment pointer.
3447 // Thus for a call through a function pointer, the following actions need
3449 // 1. Save the TOC of the caller in the TOC save area of its stack
3450 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3451 // 2. Load the address of the function entry point from the function
3453 // 3. Load the TOC of the callee from the function descriptor into r2.
3454 // 4. Load the environment pointer from the function descriptor into
3456 // 5. Branch to the function entry point address.
3457 // 6. On return of the callee, the TOC of the caller needs to be
3458 // restored (this is done in FinishCall()).
3460 // All those operations are flagged together to ensure that no other
3461 // operations can be scheduled in between. E.g. without flagging the
3462 // operations together, a TOC access in the caller could be scheduled
3463 // between the load of the callee TOC and the branch to the callee, which
3464 // results in the TOC access going through the TOC of the callee instead
3465 // of going through the TOC of the caller, which leads to incorrect code.
3467 // Load the address of the function entry point from the function
3469 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3470 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs,
3471 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3472 Chain = LoadFuncPtr.getValue(1);
3473 InFlag = LoadFuncPtr.getValue(2);
3475 // Load environment pointer into r11.
3476 // Offset of the environment pointer within the function descriptor.
3477 SDValue PtrOff = DAG.getIntPtrConstant(16);
3479 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3480 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3482 Chain = LoadEnvPtr.getValue(1);
3483 InFlag = LoadEnvPtr.getValue(2);
3485 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3487 Chain = EnvVal.getValue(0);
3488 InFlag = EnvVal.getValue(1);
3490 // Load TOC of the callee into r2. We are using a target-specific load
3491 // with r2 hard coded, because the result of a target-independent load
3492 // would never go directly into r2, since r2 is a reserved register (which
3493 // prevents the register allocator from allocating it), resulting in an
3494 // additional register being allocated and an unnecessary move instruction
3496 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3497 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3499 Chain = LoadTOCPtr.getValue(0);
3500 InFlag = LoadTOCPtr.getValue(1);
3502 MTCTROps[0] = Chain;
3503 MTCTROps[1] = LoadFuncPtr;
3504 MTCTROps[2] = InFlag;
3507 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3508 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3509 InFlag = Chain.getValue(1);
3512 NodeTys.push_back(MVT::Other);
3513 NodeTys.push_back(MVT::Glue);
3514 Ops.push_back(Chain);
3515 CallOpc = PPCISD::BCTRL;
3516 Callee.setNode(nullptr);
3517 // Add use of X11 (holding environment pointer)
3518 if (isSVR4ABI && isPPC64)
3519 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3520 // Add CTR register as callee so a bctr can be emitted later.
3522 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3525 // If this is a direct call, pass the chain and the callee.
3526 if (Callee.getNode()) {
3527 Ops.push_back(Chain);
3528 Ops.push_back(Callee);
3530 // If this is a tail call add stack pointer delta.
3532 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3534 // Add argument registers to the end of the list so that they are known live
3536 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3537 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3538 RegsToPass[i].second.getValueType()));
3544 bool isLocalCall(const SDValue &Callee)
3546 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3547 return !G->getGlobal()->isDeclaration() &&
3548 !G->getGlobal()->isWeakForLinker();
3553 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3554 CallingConv::ID CallConv, bool isVarArg,
3555 const SmallVectorImpl<ISD::InputArg> &Ins,
3556 SDLoc dl, SelectionDAG &DAG,
3557 SmallVectorImpl<SDValue> &InVals) const {
3559 SmallVector<CCValAssign, 16> RVLocs;
3560 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3561 getTargetMachine(), RVLocs, *DAG.getContext());
3562 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3564 // Copy all of the result registers out of their specified physreg.
3565 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3566 CCValAssign &VA = RVLocs[i];
3567 assert(VA.isRegLoc() && "Can only return in registers!");
3569 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3570 VA.getLocReg(), VA.getLocVT(), InFlag);
3571 Chain = Val.getValue(1);
3572 InFlag = Val.getValue(2);
3574 switch (VA.getLocInfo()) {
3575 default: llvm_unreachable("Unknown loc info!");
3576 case CCValAssign::Full: break;
3577 case CCValAssign::AExt:
3578 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3580 case CCValAssign::ZExt:
3581 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3582 DAG.getValueType(VA.getValVT()));
3583 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3585 case CCValAssign::SExt:
3586 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3587 DAG.getValueType(VA.getValVT()));
3588 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3592 InVals.push_back(Val);
3599 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3600 bool isTailCall, bool isVarArg,
3602 SmallVector<std::pair<unsigned, SDValue>, 8>
3604 SDValue InFlag, SDValue Chain,
3606 int SPDiff, unsigned NumBytes,
3607 const SmallVectorImpl<ISD::InputArg> &Ins,
3608 SmallVectorImpl<SDValue> &InVals) const {
3609 std::vector<EVT> NodeTys;
3610 SmallVector<SDValue, 8> Ops;
3611 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3612 isTailCall, RegsToPass, Ops, NodeTys,
3615 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3616 if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
3617 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3619 // When performing tail call optimization the callee pops its arguments off
3620 // the stack. Account for this here so these bytes can be pushed back on in
3621 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3622 int BytesCalleePops =
3623 (CallConv == CallingConv::Fast &&
3624 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3626 // Add a register mask operand representing the call-preserved registers.
3627 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3628 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3629 assert(Mask && "Missing call preserved mask for calling convention");
3630 Ops.push_back(DAG.getRegisterMask(Mask));
3632 if (InFlag.getNode())
3633 Ops.push_back(InFlag);
3637 assert(((Callee.getOpcode() == ISD::Register &&
3638 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3639 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3640 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3641 isa<ConstantSDNode>(Callee)) &&
3642 "Expecting an global address, external symbol, absolute value or register");
3644 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3647 // Add a NOP immediately after the branch instruction when using the 64-bit
3648 // SVR4 ABI. At link time, if caller and callee are in a different module and
3649 // thus have a different TOC, the call will be replaced with a call to a stub
3650 // function which saves the current TOC, loads the TOC of the callee and
3651 // branches to the callee. The NOP will be replaced with a load instruction
3652 // which restores the TOC of the caller from the TOC save slot of the current
3653 // stack frame. If caller and callee belong to the same module (and have the
3654 // same TOC), the NOP will remain unchanged.
3656 bool needsTOCRestore = false;
3657 if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
3658 if (CallOpc == PPCISD::BCTRL) {
3659 // This is a call through a function pointer.
3660 // Restore the caller TOC from the save area into R2.
3661 // See PrepareCall() for more information about calls through function
3662 // pointers in the 64-bit SVR4 ABI.
3663 // We are using a target-specific load with r2 hard coded, because the
3664 // result of a target-independent load would never go directly into r2,
3665 // since r2 is a reserved register (which prevents the register allocator
3666 // from allocating it), resulting in an additional register being
3667 // allocated and an unnecessary move instruction being generated.
3668 needsTOCRestore = true;
3669 } else if ((CallOpc == PPCISD::CALL) &&
3670 (!isLocalCall(Callee) ||
3671 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3672 // Otherwise insert NOP for non-local calls.
3673 CallOpc = PPCISD::CALL_NOP;
3677 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
3678 InFlag = Chain.getValue(1);
3680 if (needsTOCRestore) {
3681 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3682 Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
3683 InFlag = Chain.getValue(1);
3686 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3687 DAG.getIntPtrConstant(BytesCalleePops, true),
3690 InFlag = Chain.getValue(1);
3692 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3693 Ins, dl, DAG, InVals);
3697 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3698 SmallVectorImpl<SDValue> &InVals) const {
3699 SelectionDAG &DAG = CLI.DAG;
3701 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3702 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3703 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3704 SDValue Chain = CLI.Chain;
3705 SDValue Callee = CLI.Callee;
3706 bool &isTailCall = CLI.IsTailCall;
3707 CallingConv::ID CallConv = CLI.CallConv;
3708 bool isVarArg = CLI.IsVarArg;
3711 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3714 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
3715 report_fatal_error("failed to perform tail call elimination on a call "
3716 "site marked musttail");
3718 if (PPCSubTarget.isSVR4ABI()) {
3719 if (PPCSubTarget.isPPC64())
3720 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3721 isTailCall, Outs, OutVals, Ins,
3724 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3725 isTailCall, Outs, OutVals, Ins,
3729 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3730 isTailCall, Outs, OutVals, Ins,
3735 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3736 CallingConv::ID CallConv, bool isVarArg,
3738 const SmallVectorImpl<ISD::OutputArg> &Outs,
3739 const SmallVectorImpl<SDValue> &OutVals,
3740 const SmallVectorImpl<ISD::InputArg> &Ins,
3741 SDLoc dl, SelectionDAG &DAG,
3742 SmallVectorImpl<SDValue> &InVals) const {
3743 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3744 // of the 32-bit SVR4 ABI stack frame layout.
3746 assert((CallConv == CallingConv::C ||
3747 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3749 unsigned PtrByteSize = 4;
3751 MachineFunction &MF = DAG.getMachineFunction();
3753 // Mark this function as potentially containing a function that contains a
3754 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3755 // and restoring the callers stack pointer in this functions epilog. This is
3756 // done because by tail calling the called function might overwrite the value
3757 // in this function's (MF) stack pointer stack slot 0(SP).
3758 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3759 CallConv == CallingConv::Fast)
3760 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3762 // Count how many bytes are to be pushed on the stack, including the linkage
3763 // area, parameter list area and the part of the local variable space which
3764 // contains copies of aggregates which are passed by value.
3766 // Assign locations to all of the outgoing arguments.
3767 SmallVector<CCValAssign, 16> ArgLocs;
3768 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3769 getTargetMachine(), ArgLocs, *DAG.getContext());
3771 // Reserve space for the linkage area on the stack.
3772 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
3775 // Handle fixed and variable vector arguments differently.
3776 // Fixed vector arguments go into registers as long as registers are
3777 // available. Variable vector arguments always go into memory.
3778 unsigned NumArgs = Outs.size();
3780 for (unsigned i = 0; i != NumArgs; ++i) {
3781 MVT ArgVT = Outs[i].VT;
3782 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3785 if (Outs[i].IsFixed) {
3786 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3789 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3795 errs() << "Call operand #" << i << " has unhandled type "
3796 << EVT(ArgVT).getEVTString() << "\n";
3798 llvm_unreachable(nullptr);
3802 // All arguments are treated the same.
3803 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3806 // Assign locations to all of the outgoing aggregate by value arguments.
3807 SmallVector<CCValAssign, 16> ByValArgLocs;
3808 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3809 getTargetMachine(), ByValArgLocs, *DAG.getContext());
3811 // Reserve stack space for the allocations in CCInfo.
3812 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3814 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
3816 // Size of the linkage area, parameter list area and the part of the local
3817 // space variable where copies of aggregates which are passed by value are
3819 unsigned NumBytes = CCByValInfo.getNextStackOffset();
3821 // Calculate by how many bytes the stack has to be adjusted in case of tail
3822 // call optimization.
3823 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3825 // Adjust the stack pointer for the new arguments...
3826 // These operations are automatically eliminated by the prolog/epilog pass
3827 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3829 SDValue CallSeqStart = Chain;
3831 // Load the return address and frame pointer so it can be moved somewhere else
3834 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3837 // Set up a copy of the stack pointer for use loading and storing any
3838 // arguments that may not fit in the registers available for argument
3840 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3842 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3843 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3844 SmallVector<SDValue, 8> MemOpChains;
3846 bool seenFloatArg = false;
3847 // Walk the register/memloc assignments, inserting copies/loads.
3848 for (unsigned i = 0, j = 0, e = ArgLocs.size();
3851 CCValAssign &VA = ArgLocs[i];
3852 SDValue Arg = OutVals[i];
3853 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3855 if (Flags.isByVal()) {
3856 // Argument is an aggregate which is passed by value, thus we need to
3857 // create a copy of it in the local variable space of the current stack
3858 // frame (which is the stack frame of the caller) and pass the address of
3859 // this copy to the callee.
3860 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3861 CCValAssign &ByValVA = ByValArgLocs[j++];
3862 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3864 // Memory reserved in the local variable space of the callers stack frame.
3865 unsigned LocMemOffset = ByValVA.getLocMemOffset();
3867 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3868 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3870 // Create a copy of the argument in the local area of the current
3872 SDValue MemcpyCall =
3873 CreateCopyOfByValArgument(Arg, PtrOff,
3874 CallSeqStart.getNode()->getOperand(0),
3877 // This must go outside the CALLSEQ_START..END.
3878 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3879 CallSeqStart.getNode()->getOperand(1),
3881 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3882 NewCallSeqStart.getNode());
3883 Chain = CallSeqStart = NewCallSeqStart;
3885 // Pass the address of the aggregate copy on the stack either in a
3886 // physical register or in the parameter list area of the current stack
3887 // frame to the callee.
3891 if (VA.isRegLoc()) {
3892 if (Arg.getValueType() == MVT::i1)
3893 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
3895 seenFloatArg |= VA.getLocVT().isFloatingPoint();
3896 // Put argument in a physical register.
3897 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3899 // Put argument in the parameter list area of the current stack frame.
3900 assert(VA.isMemLoc());
3901 unsigned LocMemOffset = VA.getLocMemOffset();
3904 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3905 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3907 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3908 MachinePointerInfo(),
3911 // Calculate and remember argument location.
3912 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3918 if (!MemOpChains.empty())
3919 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3921 // Build a sequence of copy-to-reg nodes chained together with token chain
3922 // and flag operands which copy the outgoing args into the appropriate regs.
3924 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3925 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3926 RegsToPass[i].second, InFlag);
3927 InFlag = Chain.getValue(1);
3930 // Set CR bit 6 to true if this is a vararg call with floating args passed in
3933 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3934 SDValue Ops[] = { Chain, InFlag };
3936 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
3937 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
3939 InFlag = Chain.getValue(1);
3943 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3944 false, TailCallArguments);
3946 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3947 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3951 // Copy an argument into memory, being careful to do this outside the
3952 // call sequence for the call to which the argument belongs.
3954 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
3955 SDValue CallSeqStart,
3956 ISD::ArgFlagsTy Flags,
3959 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3960 CallSeqStart.getNode()->getOperand(0),
3962 // The MEMCPY must go outside the CALLSEQ_START..END.
3963 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3964 CallSeqStart.getNode()->getOperand(1),
3966 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3967 NewCallSeqStart.getNode());
3968 return NewCallSeqStart;
3972 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
3973 CallingConv::ID CallConv, bool isVarArg,
3975 const SmallVectorImpl<ISD::OutputArg> &Outs,
3976 const SmallVectorImpl<SDValue> &OutVals,
3977 const SmallVectorImpl<ISD::InputArg> &Ins,
3978 SDLoc dl, SelectionDAG &DAG,
3979 SmallVectorImpl<SDValue> &InVals) const {
3981 unsigned NumOps = Outs.size();
3983 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3984 unsigned PtrByteSize = 8;
3986 MachineFunction &MF = DAG.getMachineFunction();
3988 // Mark this function as potentially containing a function that contains a
3989 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3990 // and restoring the callers stack pointer in this functions epilog. This is
3991 // done because by tail calling the called function might overwrite the value
3992 // in this function's (MF) stack pointer stack slot 0(SP).
3993 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3994 CallConv == CallingConv::Fast)
3995 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3997 unsigned nAltivecParamsAtEnd = 0;
3999 // Count how many bytes are to be pushed on the stack, including the linkage
4000 // area, and parameter passing area. We start with at least 48 bytes, which
4001 // is reserved space for [SP][CR][LR][3 x unused].
4002 // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result
4005 CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv,
4006 Outs, OutVals, nAltivecParamsAtEnd);
4008 // Calculate by how many bytes the stack has to be adjusted in case of tail
4009 // call optimization.
4010 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4012 // To protect arguments on the stack from being clobbered in a tail call,
4013 // force all the loads to happen before doing any other lowering.
4015 Chain = DAG.getStackArgumentTokenFactor(Chain);
4017 // Adjust the stack pointer for the new arguments...
4018 // These operations are automatically eliminated by the prolog/epilog pass
4019 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4021 SDValue CallSeqStart = Chain;
4023 // Load the return address and frame pointer so it can be move somewhere else
4026 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4029 // Set up a copy of the stack pointer for use loading and storing any
4030 // arguments that may not fit in the registers available for argument
4032 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4034 // Figure out which arguments are going to go in registers, and which in
4035 // memory. Also, if this is a vararg function, floating point operations
4036 // must be stored to our stack, and loaded into integer regs as well, if
4037 // any integer regs are available for argument passing.
4038 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
4039 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4041 static const MCPhysReg GPR[] = {
4042 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4043 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4045 static const MCPhysReg *FPR = GetFPR();
4047 static const MCPhysReg VR[] = {
4048 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4049 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4051 static const MCPhysReg VSRH[] = {
4052 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4053 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4056 const unsigned NumGPRs = array_lengthof(GPR);
4057 const unsigned NumFPRs = 13;
4058 const unsigned NumVRs = array_lengthof(VR);
4060 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4061 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4063 SmallVector<SDValue, 8> MemOpChains;
4064 for (unsigned i = 0; i != NumOps; ++i) {
4065 SDValue Arg = OutVals[i];
4066 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4068 // PtrOff will be used to store the current argument to the stack if a
4069 // register cannot be found for it.
4072 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4074 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4076 // Promote integers to 64-bit values.
4077 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4078 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4079 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4080 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4083 // FIXME memcpy is used way more than necessary. Correctness first.
4084 // Note: "by value" is code for passing a structure by value, not
4086 if (Flags.isByVal()) {
4087 // Note: Size includes alignment padding, so
4088 // struct x { short a; char b; }
4089 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
4090 // These are the proper values we need for right-justifying the
4091 // aggregate in a parameter register.
4092 unsigned Size = Flags.getByValSize();
4094 // An empty aggregate parameter takes up no storage and no
4099 unsigned BVAlign = Flags.getByValAlign();
4101 if (BVAlign % PtrByteSize != 0)
4103 "ByVal alignment is not a multiple of the pointer size");
4105 ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
4108 // All aggregates smaller than 8 bytes must be passed right-justified.
4109 if (Size==1 || Size==2 || Size==4) {
4110 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4111 if (GPR_idx != NumGPRs) {
4112 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4113 MachinePointerInfo(), VT,
4115 MemOpChains.push_back(Load.getValue(1));
4116 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4118 ArgOffset += PtrByteSize;
4123 if (GPR_idx == NumGPRs && Size < 8) {
4124 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4125 PtrOff.getValueType());
4126 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4127 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4130 ArgOffset += PtrByteSize;
4133 // Copy entire object into memory. There are cases where gcc-generated
4134 // code assumes it is there, even if it could be put entirely into
4135 // registers. (This is not what the doc says.)
4137 // FIXME: The above statement is likely due to a misunderstanding of the
4138 // documents. All arguments must be copied into the parameter area BY
4139 // THE CALLEE in the event that the callee takes the address of any
4140 // formal argument. That has not yet been implemented. However, it is
4141 // reasonable to use the stack area as a staging area for the register
4144 // Skip this for small aggregates, as we will use the same slot for a
4145 // right-justified copy, below.
4147 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4151 // When a register is available, pass a small aggregate right-justified.
4152 if (Size < 8 && GPR_idx != NumGPRs) {
4153 // The easiest way to get this right-justified in a register
4154 // is to copy the structure into the rightmost portion of a
4155 // local variable slot, then load the whole slot into the
4157 // FIXME: The memcpy seems to produce pretty awful code for
4158 // small aggregates, particularly for packed ones.
4159 // FIXME: It would be preferable to use the slot in the
4160 // parameter save area instead of a new local variable.
4161 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4162 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4163 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4167 // Load the slot into the register.
4168 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4169 MachinePointerInfo(),
4170 false, false, false, 0);
4171 MemOpChains.push_back(Load.getValue(1));
4172 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4174 // Done with this argument.
4175 ArgOffset += PtrByteSize;
4179 // For aggregates larger than PtrByteSize, copy the pieces of the
4180 // object that fit into registers from the parameter save area.
4181 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4182 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4183 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4184 if (GPR_idx != NumGPRs) {
4185 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4186 MachinePointerInfo(),
4187 false, false, false, 0);
4188 MemOpChains.push_back(Load.getValue(1));
4189 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4190 ArgOffset += PtrByteSize;
4192 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4199 switch (Arg.getSimpleValueType().SimpleTy) {
4200 default: llvm_unreachable("Unexpected ValueType for argument!");
4204 if (GPR_idx != NumGPRs) {
4205 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4207 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4208 true, isTailCall, false, MemOpChains,
4209 TailCallArguments, dl);
4211 ArgOffset += PtrByteSize;
4215 if (FPR_idx != NumFPRs) {
4216 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4219 // A single float or an aggregate containing only a single float
4220 // must be passed right-justified in the stack doubleword, and
4221 // in the GPR, if one is available.
4223 if (Arg.getSimpleValueType().SimpleTy == MVT::f32) {
4224 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4225 StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4229 SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
4230 MachinePointerInfo(), false, false, 0);
4231 MemOpChains.push_back(Store);
4233 // Float varargs are always shadowed in available integer registers
4234 if (GPR_idx != NumGPRs) {
4235 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4236 MachinePointerInfo(), false, false,
4238 MemOpChains.push_back(Load.getValue(1));
4239 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4241 } else if (GPR_idx != NumGPRs)
4242 // If we have any FPRs remaining, we may also have GPRs remaining.
4245 // Single-precision floating-point values are mapped to the
4246 // second (rightmost) word of the stack doubleword.
4247 if (Arg.getValueType() == MVT::f32) {
4248 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4249 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4252 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4253 true, isTailCall, false, MemOpChains,
4254 TailCallArguments, dl);
4265 // These go aligned on the stack, or in the corresponding R registers
4266 // when within range. The Darwin PPC ABI doc claims they also go in
4267 // V registers; in fact gcc does this only for arguments that are
4268 // prototyped, not for those that match the ... We do it for all
4269 // arguments, seems to work.
4270 while (ArgOffset % 16 !=0) {
4271 ArgOffset += PtrByteSize;
4272 if (GPR_idx != NumGPRs)
4275 // We could elide this store in the case where the object fits
4276 // entirely in R registers. Maybe later.
4277 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4278 DAG.getConstant(ArgOffset, PtrVT));
4279 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4280 MachinePointerInfo(), false, false, 0);
4281 MemOpChains.push_back(Store);
4282 if (VR_idx != NumVRs) {
4283 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4284 MachinePointerInfo(),
4285 false, false, false, 0);
4286 MemOpChains.push_back(Load.getValue(1));
4288 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4289 Arg.getSimpleValueType() == MVT::v2i64) ?
4290 VSRH[VR_idx] : VR[VR_idx];
4293 RegsToPass.push_back(std::make_pair(VReg, Load));
4296 for (unsigned i=0; i<16; i+=PtrByteSize) {
4297 if (GPR_idx == NumGPRs)
4299 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4300 DAG.getConstant(i, PtrVT));
4301 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4302 false, false, false, 0);
4303 MemOpChains.push_back(Load.getValue(1));
4304 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4309 // Non-varargs Altivec params generally go in registers, but have
4310 // stack space allocated at the end.
4311 if (VR_idx != NumVRs) {
4312 // Doesn't have GPR space allocated.
4313 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4314 Arg.getSimpleValueType() == MVT::v2i64) ?
4315 VSRH[VR_idx] : VR[VR_idx];
4318 RegsToPass.push_back(std::make_pair(VReg, Arg));
4320 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4321 true, isTailCall, true, MemOpChains,
4322 TailCallArguments, dl);
4329 if (!MemOpChains.empty())
4330 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4332 // Check if this is an indirect call (MTCTR/BCTRL).
4333 // See PrepareCall() for more information about calls through function
4334 // pointers in the 64-bit SVR4 ABI.
4336 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4337 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4338 !isBLACompatibleAddress(Callee, DAG)) {
4339 // Load r2 into a virtual register and store it to the TOC save area.
4340 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4341 // TOC save area offset.
4342 SDValue PtrOff = DAG.getIntPtrConstant(40);
4343 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4344 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4346 // R12 must contain the address of an indirect callee. This does not
4347 // mean the MTCTR instruction must use R12; it's easier to model this
4348 // as an extra parameter, so do that.
4349 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4352 // Build a sequence of copy-to-reg nodes chained together with token chain
4353 // and flag operands which copy the outgoing args into the appropriate regs.
4355 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4356 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4357 RegsToPass[i].second, InFlag);
4358 InFlag = Chain.getValue(1);
4362 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4363 FPOp, true, TailCallArguments);
4365 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4366 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4371 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4372 CallingConv::ID CallConv, bool isVarArg,
4374 const SmallVectorImpl<ISD::OutputArg> &Outs,
4375 const SmallVectorImpl<SDValue> &OutVals,
4376 const SmallVectorImpl<ISD::InputArg> &Ins,
4377 SDLoc dl, SelectionDAG &DAG,
4378 SmallVectorImpl<SDValue> &InVals) const {
4380 unsigned NumOps = Outs.size();
4382 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4383 bool isPPC64 = PtrVT == MVT::i64;
4384 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4386 MachineFunction &MF = DAG.getMachineFunction();
4388 // Mark this function as potentially containing a function that contains a
4389 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4390 // and restoring the callers stack pointer in this functions epilog. This is
4391 // done because by tail calling the called function might overwrite the value
4392 // in this function's (MF) stack pointer stack slot 0(SP).
4393 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4394 CallConv == CallingConv::Fast)
4395 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4397 unsigned nAltivecParamsAtEnd = 0;
4399 // Count how many bytes are to be pushed on the stack, including the linkage
4400 // area, and parameter passing area. We start with 24/48 bytes, which is
4401 // prereserved space for [SP][CR][LR][3 x unused].
4403 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
4405 nAltivecParamsAtEnd);
4407 // Calculate by how many bytes the stack has to be adjusted in case of tail
4408 // call optimization.
4409 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4411 // To protect arguments on the stack from being clobbered in a tail call,
4412 // force all the loads to happen before doing any other lowering.
4414 Chain = DAG.getStackArgumentTokenFactor(Chain);
4416 // Adjust the stack pointer for the new arguments...
4417 // These operations are automatically eliminated by the prolog/epilog pass
4418 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4420 SDValue CallSeqStart = Chain;
4422 // Load the return address and frame pointer so it can be move somewhere else
4425 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4428 // Set up a copy of the stack pointer for use loading and storing any
4429 // arguments that may not fit in the registers available for argument
4433 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4435 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4437 // Figure out which arguments are going to go in registers, and which in
4438 // memory. Also, if this is a vararg function, floating point operations
4439 // must be stored to our stack, and loaded into integer regs as well, if
4440 // any integer regs are available for argument passing.
4441 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
4442 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4444 static const MCPhysReg GPR_32[] = { // 32-bit registers.
4445 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4446 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4448 static const MCPhysReg GPR_64[] = { // 64-bit registers.
4449 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4450 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4452 static const MCPhysReg *FPR = GetFPR();
4454 static const MCPhysReg VR[] = {
4455 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4456 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4458 const unsigned NumGPRs = array_lengthof(GPR_32);
4459 const unsigned NumFPRs = 13;
4460 const unsigned NumVRs = array_lengthof(VR);
4462 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4464 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4465 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4467 SmallVector<SDValue, 8> MemOpChains;
4468 for (unsigned i = 0; i != NumOps; ++i) {
4469 SDValue Arg = OutVals[i];
4470 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4472 // PtrOff will be used to store the current argument to the stack if a
4473 // register cannot be found for it.
4476 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4478 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4480 // On PPC64, promote integers to 64-bit values.
4481 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4482 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4483 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4484 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4487 // FIXME memcpy is used way more than necessary. Correctness first.
4488 // Note: "by value" is code for passing a structure by value, not
4490 if (Flags.isByVal()) {
4491 unsigned Size = Flags.getByValSize();
4492 // Very small objects are passed right-justified. Everything else is
4493 // passed left-justified.
4494 if (Size==1 || Size==2) {
4495 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4496 if (GPR_idx != NumGPRs) {
4497 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4498 MachinePointerInfo(), VT,
4500 MemOpChains.push_back(Load.getValue(1));
4501 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4503 ArgOffset += PtrByteSize;
4505 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4506 PtrOff.getValueType());
4507 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4508 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4511 ArgOffset += PtrByteSize;
4515 // Copy entire object into memory. There are cases where gcc-generated
4516 // code assumes it is there, even if it could be put entirely into
4517 // registers. (This is not what the doc says.)
4518 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4522 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4523 // copy the pieces of the object that fit into registers from the
4524 // parameter save area.
4525 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4526 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4527 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4528 if (GPR_idx != NumGPRs) {
4529 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4530 MachinePointerInfo(),
4531 false, false, false, 0);
4532 MemOpChains.push_back(Load.getValue(1));
4533 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4534 ArgOffset += PtrByteSize;
4536 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4543 switch (Arg.getSimpleValueType().SimpleTy) {
4544 default: llvm_unreachable("Unexpected ValueType for argument!");
4548 if (GPR_idx != NumGPRs) {
4549 if (Arg.getValueType() == MVT::i1)
4550 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4552 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4554 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4555 isPPC64, isTailCall, false, MemOpChains,
4556 TailCallArguments, dl);
4558 ArgOffset += PtrByteSize;
4562 if (FPR_idx != NumFPRs) {
4563 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4566 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4567 MachinePointerInfo(), false, false, 0);
4568 MemOpChains.push_back(Store);
4570 // Float varargs are always shadowed in available integer registers
4571 if (GPR_idx != NumGPRs) {
4572 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4573 MachinePointerInfo(), false, false,
4575 MemOpChains.push_back(Load.getValue(1));
4576 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4578 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4579 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4580 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4581 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4582 MachinePointerInfo(),
4583 false, false, false, 0);
4584 MemOpChains.push_back(Load.getValue(1));
4585 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4588 // If we have any FPRs remaining, we may also have GPRs remaining.
4589 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4591 if (GPR_idx != NumGPRs)
4593 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4594 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4598 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4599 isPPC64, isTailCall, false, MemOpChains,
4600 TailCallArguments, dl);
4604 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4611 // These go aligned on the stack, or in the corresponding R registers
4612 // when within range. The Darwin PPC ABI doc claims they also go in
4613 // V registers; in fact gcc does this only for arguments that are
4614 // prototyped, not for those that match the ... We do it for all
4615 // arguments, seems to work.
4616 while (ArgOffset % 16 !=0) {
4617 ArgOffset += PtrByteSize;
4618 if (GPR_idx != NumGPRs)
4621 // We could elide this store in the case where the object fits
4622 // entirely in R registers. Maybe later.
4623 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4624 DAG.getConstant(ArgOffset, PtrVT));
4625 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4626 MachinePointerInfo(), false, false, 0);
4627 MemOpChains.push_back(Store);
4628 if (VR_idx != NumVRs) {
4629 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4630 MachinePointerInfo(),
4631 false, false, false, 0);
4632 MemOpChains.push_back(Load.getValue(1));
4633 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4636 for (unsigned i=0; i<16; i+=PtrByteSize) {
4637 if (GPR_idx == NumGPRs)
4639 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4640 DAG.getConstant(i, PtrVT));
4641 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4642 false, false, false, 0);
4643 MemOpChains.push_back(Load.getValue(1));
4644 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4649 // Non-varargs Altivec params generally go in registers, but have
4650 // stack space allocated at the end.
4651 if (VR_idx != NumVRs) {
4652 // Doesn't have GPR space allocated.
4653 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4654 } else if (nAltivecParamsAtEnd==0) {
4655 // We are emitting Altivec params in order.
4656 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4657 isPPC64, isTailCall, true, MemOpChains,
4658 TailCallArguments, dl);
4664 // If all Altivec parameters fit in registers, as they usually do,
4665 // they get stack space following the non-Altivec parameters. We
4666 // don't track this here because nobody below needs it.
4667 // If there are more Altivec parameters than fit in registers emit
4669 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4671 // Offset is aligned; skip 1st 12 params which go in V registers.
4672 ArgOffset = ((ArgOffset+15)/16)*16;
4674 for (unsigned i = 0; i != NumOps; ++i) {
4675 SDValue Arg = OutVals[i];
4676 EVT ArgType = Outs[i].VT;
4677 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4678 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4681 // We are emitting Altivec params in order.
4682 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4683 isPPC64, isTailCall, true, MemOpChains,
4684 TailCallArguments, dl);
4691 if (!MemOpChains.empty())
4692 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4694 // On Darwin, R12 must contain the address of an indirect callee. This does
4695 // not mean the MTCTR instruction must use R12; it's easier to model this as
4696 // an extra parameter, so do that.
4698 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4699 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4700 !isBLACompatibleAddress(Callee, DAG))
4701 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4702 PPC::R12), Callee));
4704 // Build a sequence of copy-to-reg nodes chained together with token chain
4705 // and flag operands which copy the outgoing args into the appropriate regs.
4707 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4708 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4709 RegsToPass[i].second, InFlag);
4710 InFlag = Chain.getValue(1);
4714 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4715 FPOp, true, TailCallArguments);
4717 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4718 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4723 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4724 MachineFunction &MF, bool isVarArg,
4725 const SmallVectorImpl<ISD::OutputArg> &Outs,
4726 LLVMContext &Context) const {
4727 SmallVector<CCValAssign, 16> RVLocs;
4728 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4730 return CCInfo.CheckReturn(Outs, RetCC_PPC);
4734 PPCTargetLowering::LowerReturn(SDValue Chain,
4735 CallingConv::ID CallConv, bool isVarArg,
4736 const SmallVectorImpl<ISD::OutputArg> &Outs,
4737 const SmallVectorImpl<SDValue> &OutVals,
4738 SDLoc dl, SelectionDAG &DAG) const {
4740 SmallVector<CCValAssign, 16> RVLocs;
4741 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4742 getTargetMachine(), RVLocs, *DAG.getContext());
4743 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4746 SmallVector<SDValue, 4> RetOps(1, Chain);
4748 // Copy the result values into the output registers.
4749 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4750 CCValAssign &VA = RVLocs[i];
4751 assert(VA.isRegLoc() && "Can only return in registers!");
4753 SDValue Arg = OutVals[i];
4755 switch (VA.getLocInfo()) {
4756 default: llvm_unreachable("Unknown loc info!");
4757 case CCValAssign::Full: break;
4758 case CCValAssign::AExt:
4759 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4761 case CCValAssign::ZExt:
4762 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4764 case CCValAssign::SExt:
4765 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4769 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4770 Flag = Chain.getValue(1);
4771 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4774 RetOps[0] = Chain; // Update chain.
4776 // Add the flag if we have it.
4778 RetOps.push_back(Flag);
4780 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
4783 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4784 const PPCSubtarget &Subtarget) const {
4785 // When we pop the dynamic allocation we need to restore the SP link.
4788 // Get the corect type for pointers.
4789 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4791 // Construct the stack pointer operand.
4792 bool isPPC64 = Subtarget.isPPC64();
4793 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4794 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4796 // Get the operands for the STACKRESTORE.
4797 SDValue Chain = Op.getOperand(0);
4798 SDValue SaveSP = Op.getOperand(1);
4800 // Load the old link SP.
4801 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4802 MachinePointerInfo(),
4803 false, false, false, 0);
4805 // Restore the stack pointer.
4806 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4808 // Store the old link SP.
4809 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4816 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4817 MachineFunction &MF = DAG.getMachineFunction();
4818 bool isPPC64 = PPCSubTarget.isPPC64();
4819 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4820 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4822 // Get current frame pointer save index. The users of this index will be
4823 // primarily DYNALLOC instructions.
4824 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4825 int RASI = FI->getReturnAddrSaveIndex();
4827 // If the frame pointer save index hasn't been defined yet.
4829 // Find out what the fix offset of the frame pointer save area.
4830 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4831 // Allocate the frame index for frame pointer save area.
4832 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4834 FI->setReturnAddrSaveIndex(RASI);
4836 return DAG.getFrameIndex(RASI, PtrVT);
4840 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
4841 MachineFunction &MF = DAG.getMachineFunction();
4842 bool isPPC64 = PPCSubTarget.isPPC64();
4843 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4844 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4846 // Get current frame pointer save index. The users of this index will be
4847 // primarily DYNALLOC instructions.
4848 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4849 int FPSI = FI->getFramePointerSaveIndex();
4851 // If the frame pointer save index hasn't been defined yet.
4853 // Find out what the fix offset of the frame pointer save area.
4854 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
4857 // Allocate the frame index for frame pointer save area.
4858 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
4860 FI->setFramePointerSaveIndex(FPSI);
4862 return DAG.getFrameIndex(FPSI, PtrVT);
4865 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4867 const PPCSubtarget &Subtarget) const {
4869 SDValue Chain = Op.getOperand(0);
4870 SDValue Size = Op.getOperand(1);
4873 // Get the corect type for pointers.
4874 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4876 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
4877 DAG.getConstant(0, PtrVT), Size);
4878 // Construct a node for the frame pointer save index.
4879 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
4880 // Build a DYNALLOC node.
4881 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
4882 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
4883 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
4886 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
4887 SelectionDAG &DAG) const {
4889 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
4890 DAG.getVTList(MVT::i32, MVT::Other),
4891 Op.getOperand(0), Op.getOperand(1));
4894 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
4895 SelectionDAG &DAG) const {
4897 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
4898 Op.getOperand(0), Op.getOperand(1));
4901 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
4902 assert(Op.getValueType() == MVT::i1 &&
4903 "Custom lowering only for i1 loads");
4905 // First, load 8 bits into 32 bits, then truncate to 1 bit.
4908 LoadSDNode *LD = cast<LoadSDNode>(Op);
4910 SDValue Chain = LD->getChain();
4911 SDValue BasePtr = LD->getBasePtr();
4912 MachineMemOperand *MMO = LD->getMemOperand();
4914 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
4915 BasePtr, MVT::i8, MMO);
4916 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
4918 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
4919 return DAG.getMergeValues(Ops, dl);
4922 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
4923 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
4924 "Custom lowering only for i1 stores");
4926 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
4929 StoreSDNode *ST = cast<StoreSDNode>(Op);
4931 SDValue Chain = ST->getChain();
4932 SDValue BasePtr = ST->getBasePtr();
4933 SDValue Value = ST->getValue();
4934 MachineMemOperand *MMO = ST->getMemOperand();
4936 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
4937 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
4940 // FIXME: Remove this once the ANDI glue bug is fixed:
4941 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
4942 assert(Op.getValueType() == MVT::i1 &&
4943 "Custom lowering only for i1 results");
4946 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
4950 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
4952 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4953 // Not FP? Not a fsel.
4954 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
4955 !Op.getOperand(2).getValueType().isFloatingPoint())
4958 // We might be able to do better than this under some circumstances, but in
4959 // general, fsel-based lowering of select is a finite-math-only optimization.
4960 // For more information, see section F.3 of the 2.06 ISA specification.
4961 if (!DAG.getTarget().Options.NoInfsFPMath ||
4962 !DAG.getTarget().Options.NoNaNsFPMath)
4965 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4967 EVT ResVT = Op.getValueType();
4968 EVT CmpVT = Op.getOperand(0).getValueType();
4969 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4970 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
4973 // If the RHS of the comparison is a 0.0, we don't need to do the
4974 // subtraction at all.
4976 if (isFloatingPointZero(RHS))
4978 default: break; // SETUO etc aren't handled by fsel.
4982 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4983 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4984 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4985 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
4986 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4987 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4988 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
4991 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4994 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4995 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4996 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4999 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5002 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5003 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5004 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5005 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5010 default: break; // SETUO etc aren't handled by fsel.
5014 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5015 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5016 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5017 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5018 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5019 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5020 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5021 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5024 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5025 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5026 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5027 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5030 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5031 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5032 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5033 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5036 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5037 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5038 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5039 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5042 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5043 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5044 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5045 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5050 // FIXME: Split this code up when LegalizeDAGTypes lands.
5051 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5053 assert(Op.getOperand(0).getValueType().isFloatingPoint());
5054 SDValue Src = Op.getOperand(0);
5055 if (Src.getValueType() == MVT::f32)
5056 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5059 switch (Op.getSimpleValueType().SimpleTy) {
5060 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5062 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
5063 (PPCSubTarget.hasFPCVT() ? PPCISD::FCTIWUZ :
5068 assert((Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT()) &&
5069 "i64 FP_TO_UINT is supported only with FPCVT");
5070 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5076 // Convert the FP value to an int value through memory.
5077 bool i32Stack = Op.getValueType() == MVT::i32 && PPCSubTarget.hasSTFIWX() &&
5078 (Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT());
5079 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5080 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5081 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5083 // Emit a store to the stack slot.
5086 MachineFunction &MF = DAG.getMachineFunction();
5087 MachineMemOperand *MMO =
5088 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5089 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5090 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5091 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5093 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5094 MPI, false, false, 0);
5096 // Result is a load from the stack slot. If loading 4 bytes, make sure to
5098 if (Op.getValueType() == MVT::i32 && !i32Stack) {
5099 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5100 DAG.getConstant(4, FIPtr.getValueType()));
5101 MPI = MachinePointerInfo();
5104 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
5105 false, false, false, 0);
5108 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5109 SelectionDAG &DAG) const {
5111 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5112 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5115 if (Op.getOperand(0).getValueType() == MVT::i1)
5116 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5117 DAG.getConstantFP(1.0, Op.getValueType()),
5118 DAG.getConstantFP(0.0, Op.getValueType()));
5120 assert((Op.getOpcode() == ISD::SINT_TO_FP || PPCSubTarget.hasFPCVT()) &&
5121 "UINT_TO_FP is supported only with FPCVT");
5123 // If we have FCFIDS, then use it when converting to single-precision.
5124 // Otherwise, convert to double-precision and then round.
5125 unsigned FCFOp = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5126 (Op.getOpcode() == ISD::UINT_TO_FP ?
5127 PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5128 (Op.getOpcode() == ISD::UINT_TO_FP ?
5129 PPCISD::FCFIDU : PPCISD::FCFID);
5130 MVT FCFTy = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5131 MVT::f32 : MVT::f64;
5133 if (Op.getOperand(0).getValueType() == MVT::i64) {
5134 SDValue SINT = Op.getOperand(0);
5135 // When converting to single-precision, we actually need to convert
5136 // to double-precision first and then round to single-precision.
5137 // To avoid double-rounding effects during that operation, we have
5138 // to prepare the input operand. Bits that might be truncated when
5139 // converting to double-precision are replaced by a bit that won't
5140 // be lost at this stage, but is below the single-precision rounding
5143 // However, if -enable-unsafe-fp-math is in effect, accept double
5144 // rounding to avoid the extra overhead.
5145 if (Op.getValueType() == MVT::f32 &&
5146 !PPCSubTarget.hasFPCVT() &&
5147 !DAG.getTarget().Options.UnsafeFPMath) {
5149 // Twiddle input to make sure the low 11 bits are zero. (If this
5150 // is the case, we are guaranteed the value will fit into the 53 bit
5151 // mantissa of an IEEE double-precision value without rounding.)
5152 // If any of those low 11 bits were not zero originally, make sure
5153 // bit 12 (value 2048) is set instead, so that the final rounding
5154 // to single-precision gets the correct result.
5155 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5156 SINT, DAG.getConstant(2047, MVT::i64));
5157 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5158 Round, DAG.getConstant(2047, MVT::i64));
5159 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5160 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5161 Round, DAG.getConstant(-2048, MVT::i64));
5163 // However, we cannot use that value unconditionally: if the magnitude
5164 // of the input value is small, the bit-twiddling we did above might
5165 // end up visibly changing the output. Fortunately, in that case, we
5166 // don't need to twiddle bits since the original input will convert
5167 // exactly to double-precision floating-point already. Therefore,
5168 // construct a conditional to use the original value if the top 11
5169 // bits are all sign-bit copies, and use the rounded value computed
5171 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5172 SINT, DAG.getConstant(53, MVT::i32));
5173 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5174 Cond, DAG.getConstant(1, MVT::i64));
5175 Cond = DAG.getSetCC(dl, MVT::i32,
5176 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5178 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5181 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5182 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5184 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5185 FP = DAG.getNode(ISD::FP_ROUND, dl,
5186 MVT::f32, FP, DAG.getIntPtrConstant(0));
5190 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5191 "Unhandled INT_TO_FP type in custom expander!");
5192 // Since we only generate this in 64-bit mode, we can take advantage of
5193 // 64-bit registers. In particular, sign extend the input value into the
5194 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5195 // then lfd it and fcfid it.
5196 MachineFunction &MF = DAG.getMachineFunction();
5197 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5198 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5201 if (PPCSubTarget.hasLFIWAX() || PPCSubTarget.hasFPCVT()) {
5202 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5203 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5205 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5206 MachinePointerInfo::getFixedStack(FrameIdx),
5209 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5210 "Expected an i32 store");
5211 MachineMemOperand *MMO =
5212 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
5213 MachineMemOperand::MOLoad, 4, 4);
5214 SDValue Ops[] = { Store, FIdx };
5215 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5216 PPCISD::LFIWZX : PPCISD::LFIWAX,
5217 dl, DAG.getVTList(MVT::f64, MVT::Other),
5218 Ops, MVT::i32, MMO);
5220 assert(PPCSubTarget.isPPC64() &&
5221 "i32->FP without LFIWAX supported only on PPC64");
5223 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5224 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5226 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5229 // STD the extended value into the stack slot.
5230 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5231 MachinePointerInfo::getFixedStack(FrameIdx),
5234 // Load the value as a double.
5235 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5236 MachinePointerInfo::getFixedStack(FrameIdx),
5237 false, false, false, 0);
5240 // FCFID it and return it.
5241 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5242 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5243 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5247 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5248 SelectionDAG &DAG) const {
5251 The rounding mode is in bits 30:31 of FPSR, and has the following
5258 FLT_ROUNDS, on the other hand, expects the following:
5265 To perform the conversion, we do:
5266 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5269 MachineFunction &MF = DAG.getMachineFunction();
5270 EVT VT = Op.getValueType();
5271 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5273 // Save FP Control Word to register
5275 MVT::f64, // return register
5276 MVT::Glue // unused in this context
5278 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
5280 // Save FP register to stack slot
5281 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5282 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5283 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5284 StackSlot, MachinePointerInfo(), false, false,0);
5286 // Load FP Control Word from low 32 bits of stack slot.
5287 SDValue Four = DAG.getConstant(4, PtrVT);
5288 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5289 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5290 false, false, false, 0);
5292 // Transform as necessary
5294 DAG.getNode(ISD::AND, dl, MVT::i32,
5295 CWD, DAG.getConstant(3, MVT::i32));
5297 DAG.getNode(ISD::SRL, dl, MVT::i32,
5298 DAG.getNode(ISD::AND, dl, MVT::i32,
5299 DAG.getNode(ISD::XOR, dl, MVT::i32,
5300 CWD, DAG.getConstant(3, MVT::i32)),
5301 DAG.getConstant(3, MVT::i32)),
5302 DAG.getConstant(1, MVT::i32));
5305 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5307 return DAG.getNode((VT.getSizeInBits() < 16 ?
5308 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5311 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5312 EVT VT = Op.getValueType();
5313 unsigned BitWidth = VT.getSizeInBits();
5315 assert(Op.getNumOperands() == 3 &&
5316 VT == Op.getOperand(1).getValueType() &&
5319 // Expand into a bunch of logical ops. Note that these ops
5320 // depend on the PPC behavior for oversized shift amounts.
5321 SDValue Lo = Op.getOperand(0);
5322 SDValue Hi = Op.getOperand(1);
5323 SDValue Amt = Op.getOperand(2);
5324 EVT AmtVT = Amt.getValueType();
5326 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5327 DAG.getConstant(BitWidth, AmtVT), Amt);
5328 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5329 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5330 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5331 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5332 DAG.getConstant(-BitWidth, AmtVT));
5333 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5334 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5335 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5336 SDValue OutOps[] = { OutLo, OutHi };
5337 return DAG.getMergeValues(OutOps, dl);
5340 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5341 EVT VT = Op.getValueType();
5343 unsigned BitWidth = VT.getSizeInBits();
5344 assert(Op.getNumOperands() == 3 &&
5345 VT == Op.getOperand(1).getValueType() &&
5348 // Expand into a bunch of logical ops. Note that these ops
5349 // depend on the PPC behavior for oversized shift amounts.
5350 SDValue Lo = Op.getOperand(0);
5351 SDValue Hi = Op.getOperand(1);
5352 SDValue Amt = Op.getOperand(2);
5353 EVT AmtVT = Amt.getValueType();
5355 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5356 DAG.getConstant(BitWidth, AmtVT), Amt);
5357 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5358 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5359 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5360 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5361 DAG.getConstant(-BitWidth, AmtVT));
5362 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5363 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5364 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5365 SDValue OutOps[] = { OutLo, OutHi };
5366 return DAG.getMergeValues(OutOps, dl);
5369 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5371 EVT VT = Op.getValueType();
5372 unsigned BitWidth = VT.getSizeInBits();
5373 assert(Op.getNumOperands() == 3 &&
5374 VT == Op.getOperand(1).getValueType() &&
5377 // Expand into a bunch of logical ops, followed by a select_cc.
5378 SDValue Lo = Op.getOperand(0);
5379 SDValue Hi = Op.getOperand(1);
5380 SDValue Amt = Op.getOperand(2);
5381 EVT AmtVT = Amt.getValueType();
5383 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5384 DAG.getConstant(BitWidth, AmtVT), Amt);
5385 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5386 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5387 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5388 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5389 DAG.getConstant(-BitWidth, AmtVT));
5390 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5391 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5392 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5393 Tmp4, Tmp6, ISD::SETLE);
5394 SDValue OutOps[] = { OutLo, OutHi };
5395 return DAG.getMergeValues(OutOps, dl);
5398 //===----------------------------------------------------------------------===//
5399 // Vector related lowering.
5402 /// BuildSplatI - Build a canonical splati of Val with an element size of
5403 /// SplatSize. Cast the result to VT.
5404 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5405 SelectionDAG &DAG, SDLoc dl) {
5406 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5408 static const EVT VTys[] = { // canonical VT to use for each size.
5409 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5412 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5414 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5418 EVT CanonicalVT = VTys[SplatSize-1];
5420 // Build a canonical splat for this value.
5421 SDValue Elt = DAG.getConstant(Val, MVT::i32);
5422 SmallVector<SDValue, 8> Ops;
5423 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5424 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
5425 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5428 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5429 /// specified intrinsic ID.
5430 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5431 SelectionDAG &DAG, SDLoc dl,
5432 EVT DestVT = MVT::Other) {
5433 if (DestVT == MVT::Other) DestVT = Op.getValueType();
5434 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5435 DAG.getConstant(IID, MVT::i32), Op);
5438 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5439 /// specified intrinsic ID.
5440 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5441 SelectionDAG &DAG, SDLoc dl,
5442 EVT DestVT = MVT::Other) {
5443 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5444 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5445 DAG.getConstant(IID, MVT::i32), LHS, RHS);
5448 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5449 /// specified intrinsic ID.
5450 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5451 SDValue Op2, SelectionDAG &DAG,
5452 SDLoc dl, EVT DestVT = MVT::Other) {
5453 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5454 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5455 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5459 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5460 /// amount. The result has the specified value type.
5461 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5462 EVT VT, SelectionDAG &DAG, SDLoc dl) {
5463 // Force LHS/RHS to be the right type.
5464 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5465 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5468 for (unsigned i = 0; i != 16; ++i)
5470 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5471 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5474 // If this is a case we can't handle, return null and let the default
5475 // expansion code take care of it. If we CAN select this case, and if it
5476 // selects to a single instruction, return Op. Otherwise, if we can codegen
5477 // this case more efficiently than a constant pool load, lower it to the
5478 // sequence of ops that should be used.
5479 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5480 SelectionDAG &DAG) const {
5482 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5483 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5485 // Check if this is a splat of a constant value.
5486 APInt APSplatBits, APSplatUndef;
5487 unsigned SplatBitSize;
5489 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5490 HasAnyUndefs, 0, true) || SplatBitSize > 32)
5493 unsigned SplatBits = APSplatBits.getZExtValue();
5494 unsigned SplatUndef = APSplatUndef.getZExtValue();
5495 unsigned SplatSize = SplatBitSize / 8;
5497 // First, handle single instruction cases.
5500 if (SplatBits == 0) {
5501 // Canonicalize all zero vectors to be v4i32.
5502 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5503 SDValue Z = DAG.getConstant(0, MVT::i32);
5504 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5505 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5510 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5511 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5513 if (SextVal >= -16 && SextVal <= 15)
5514 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5517 // Two instruction sequences.
5519 // If this value is in the range [-32,30] and is even, use:
5520 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5521 // If this value is in the range [17,31] and is odd, use:
5522 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5523 // If this value is in the range [-31,-17] and is odd, use:
5524 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5525 // Note the last two are three-instruction sequences.
5526 if (SextVal >= -32 && SextVal <= 31) {
5527 // To avoid having these optimizations undone by constant folding,
5528 // we convert to a pseudo that will be expanded later into one of
5530 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5531 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
5532 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
5533 SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
5534 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5535 if (VT == Op.getValueType())
5538 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
5541 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
5542 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
5544 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5545 // Make -1 and vspltisw -1:
5546 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5548 // Make the VSLW intrinsic, computing 0x8000_0000.
5549 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5552 // xor by OnesV to invert it.
5553 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5554 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5557 // Check to see if this is a wide variety of vsplti*, binop self cases.
5558 static const signed char SplatCsts[] = {
5559 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5560 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5563 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5564 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5565 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
5566 int i = SplatCsts[idx];
5568 // Figure out what shift amount will be used by altivec if shifted by i in
5570 unsigned TypeShiftAmt = i & (SplatBitSize-1);
5572 // vsplti + shl self.
5573 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5574 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5575 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5576 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5577 Intrinsic::ppc_altivec_vslw
5579 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5580 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5583 // vsplti + srl self.
5584 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5585 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5586 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5587 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5588 Intrinsic::ppc_altivec_vsrw
5590 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5591 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5594 // vsplti + sra self.
5595 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5596 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5597 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5598 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5599 Intrinsic::ppc_altivec_vsraw
5601 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5602 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5605 // vsplti + rol self.
5606 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5607 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5608 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5609 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5610 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5611 Intrinsic::ppc_altivec_vrlw
5613 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5614 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5617 // t = vsplti c, result = vsldoi t, t, 1
5618 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5619 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5620 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5622 // t = vsplti c, result = vsldoi t, t, 2
5623 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5624 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5625 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5627 // t = vsplti c, result = vsldoi t, t, 3
5628 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5629 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5630 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5637 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5638 /// the specified operations to build the shuffle.
5639 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5640 SDValue RHS, SelectionDAG &DAG,
5642 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5643 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5644 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5647 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5659 if (OpNum == OP_COPY) {
5660 if (LHSID == (1*9+2)*9+3) return LHS;
5661 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5665 SDValue OpLHS, OpRHS;
5666 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5667 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5671 default: llvm_unreachable("Unknown i32 permute!");
5673 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
5674 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5675 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
5676 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5679 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5680 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5681 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5682 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5685 for (unsigned i = 0; i != 16; ++i)
5686 ShufIdxs[i] = (i&3)+0;
5689 for (unsigned i = 0; i != 16; ++i)
5690 ShufIdxs[i] = (i&3)+4;
5693 for (unsigned i = 0; i != 16; ++i)
5694 ShufIdxs[i] = (i&3)+8;
5697 for (unsigned i = 0; i != 16; ++i)
5698 ShufIdxs[i] = (i&3)+12;
5701 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5703 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5705 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5707 EVT VT = OpLHS.getValueType();
5708 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5709 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5710 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5711 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5714 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
5715 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
5716 /// return the code it can be lowered into. Worst case, it can always be
5717 /// lowered into a vperm.
5718 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5719 SelectionDAG &DAG) const {
5721 SDValue V1 = Op.getOperand(0);
5722 SDValue V2 = Op.getOperand(1);
5723 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5724 EVT VT = Op.getValueType();
5726 // Cases that are handled by instructions that take permute immediates
5727 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5728 // selected by the instruction selector.
5729 if (V2.getOpcode() == ISD::UNDEF) {
5730 if (PPC::isSplatShuffleMask(SVOp, 1) ||
5731 PPC::isSplatShuffleMask(SVOp, 2) ||
5732 PPC::isSplatShuffleMask(SVOp, 4) ||
5733 PPC::isVPKUWUMShuffleMask(SVOp, true) ||
5734 PPC::isVPKUHUMShuffleMask(SVOp, true) ||
5735 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
5736 PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
5737 PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
5738 PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
5739 PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
5740 PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
5741 PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
5746 // Altivec has a variety of "shuffle immediates" that take two vector inputs
5747 // and produce a fixed permutation. If any of these match, do not lower to
5749 if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
5750 PPC::isVPKUHUMShuffleMask(SVOp, false) ||
5751 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
5752 PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
5753 PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
5754 PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
5755 PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
5756 PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
5757 PPC::isVMRGHShuffleMask(SVOp, 4, false))
5760 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
5761 // perfect shuffle table to emit an optimal matching sequence.
5762 ArrayRef<int> PermMask = SVOp->getMask();
5764 unsigned PFIndexes[4];
5765 bool isFourElementShuffle = true;
5766 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5767 unsigned EltNo = 8; // Start out undef.
5768 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
5769 if (PermMask[i*4+j] < 0)
5770 continue; // Undef, ignore it.
5772 unsigned ByteSource = PermMask[i*4+j];
5773 if ((ByteSource & 3) != j) {
5774 isFourElementShuffle = false;
5779 EltNo = ByteSource/4;
5780 } else if (EltNo != ByteSource/4) {
5781 isFourElementShuffle = false;
5785 PFIndexes[i] = EltNo;
5788 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5789 // perfect shuffle vector to determine if it is cost effective to do this as
5790 // discrete instructions, or whether we should use a vperm.
5791 if (isFourElementShuffle) {
5792 // Compute the index in the perfect shuffle table.
5793 unsigned PFTableIndex =
5794 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5796 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5797 unsigned Cost = (PFEntry >> 30);
5799 // Determining when to avoid vperm is tricky. Many things affect the cost
5800 // of vperm, particularly how many times the perm mask needs to be computed.
5801 // For example, if the perm mask can be hoisted out of a loop or is already
5802 // used (perhaps because there are multiple permutes with the same shuffle
5803 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
5804 // the loop requires an extra register.
5806 // As a compromise, we only emit discrete instructions if the shuffle can be
5807 // generated in 3 or fewer operations. When we have loop information
5808 // available, if this block is within a loop, we should avoid using vperm
5809 // for 3-operation perms and use a constant pool load instead.
5811 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5814 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5815 // vector that will get spilled to the constant pool.
5816 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5818 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
5819 // that it is in input element units, not in bytes. Convert now.
5820 EVT EltVT = V1.getValueType().getVectorElementType();
5821 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
5823 SmallVector<SDValue, 16> ResultMask;
5824 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5825 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
5827 for (unsigned j = 0; j != BytesPerElement; ++j)
5828 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
5832 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
5834 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
5837 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
5838 /// altivec comparison. If it is, return true and fill in Opc/isDot with
5839 /// information about the intrinsic.
5840 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
5842 unsigned IntrinsicID =
5843 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
5846 switch (IntrinsicID) {
5847 default: return false;
5848 // Comparison predicates.
5849 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
5850 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
5851 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
5852 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
5853 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
5854 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
5855 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
5856 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
5857 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
5858 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
5859 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
5860 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
5861 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
5863 // Normal Comparisons.
5864 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
5865 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
5866 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
5867 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
5868 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
5869 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
5870 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
5871 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
5872 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
5873 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
5874 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
5875 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
5876 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
5881 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
5882 /// lower, do it, otherwise return null.
5883 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5884 SelectionDAG &DAG) const {
5885 // If this is a lowered altivec predicate compare, CompareOpc is set to the
5886 // opcode number of the comparison.
5890 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
5891 return SDValue(); // Don't custom lower most intrinsics.
5893 // If this is a non-dot comparison, make the VCMP node and we are done.
5895 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
5896 Op.getOperand(1), Op.getOperand(2),
5897 DAG.getConstant(CompareOpc, MVT::i32));
5898 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
5901 // Create the PPCISD altivec 'dot' comparison node.
5903 Op.getOperand(2), // LHS
5904 Op.getOperand(3), // RHS
5905 DAG.getConstant(CompareOpc, MVT::i32)
5907 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
5908 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
5910 // Now that we have the comparison, emit a copy from the CR to a GPR.
5911 // This is flagged to the above dot comparison.
5912 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
5913 DAG.getRegister(PPC::CR6, MVT::i32),
5914 CompNode.getValue(1));
5916 // Unpack the result based on how the target uses it.
5917 unsigned BitNo; // Bit # of CR6.
5918 bool InvertBit; // Invert result?
5919 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
5920 default: // Can't happen, don't crash on invalid number though.
5921 case 0: // Return the value of the EQ bit of CR6.
5922 BitNo = 0; InvertBit = false;
5924 case 1: // Return the inverted value of the EQ bit of CR6.
5925 BitNo = 0; InvertBit = true;
5927 case 2: // Return the value of the LT bit of CR6.
5928 BitNo = 2; InvertBit = false;
5930 case 3: // Return the inverted value of the LT bit of CR6.
5931 BitNo = 2; InvertBit = true;
5935 // Shift the bit into the low position.
5936 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
5937 DAG.getConstant(8-(3-BitNo), MVT::i32));
5939 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
5940 DAG.getConstant(1, MVT::i32));
5942 // If we are supposed to, toggle the bit.
5944 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
5945 DAG.getConstant(1, MVT::i32));
5949 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
5950 SelectionDAG &DAG) const {
5952 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
5953 // instructions), but for smaller types, we need to first extend up to v2i32
5954 // before doing going farther.
5955 if (Op.getValueType() == MVT::v2i64) {
5956 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
5957 if (ExtVT != MVT::v2i32) {
5958 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
5959 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
5960 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
5961 ExtVT.getVectorElementType(), 4)));
5962 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
5963 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
5964 DAG.getValueType(MVT::v2i32));
5973 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
5974 SelectionDAG &DAG) const {
5976 // Create a stack slot that is 16-byte aligned.
5977 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5978 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
5979 EVT PtrVT = getPointerTy();
5980 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5982 // Store the input value into Value#0 of the stack slot.
5983 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
5984 Op.getOperand(0), FIdx, MachinePointerInfo(),
5987 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
5988 false, false, false, 0);
5991 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
5993 if (Op.getValueType() == MVT::v4i32) {
5994 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5996 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
5997 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
5999 SDValue RHSSwap = // = vrlw RHS, 16
6000 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6002 // Shrinkify inputs to v8i16.
6003 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6004 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6005 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6007 // Low parts multiplied together, generating 32-bit results (we ignore the
6009 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6010 LHS, RHS, DAG, dl, MVT::v4i32);
6012 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6013 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6014 // Shift the high parts up 16 bits.
6015 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6017 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6018 } else if (Op.getValueType() == MVT::v8i16) {
6019 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6021 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6023 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6024 LHS, RHS, Zero, DAG, dl);
6025 } else if (Op.getValueType() == MVT::v16i8) {
6026 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6028 // Multiply the even 8-bit parts, producing 16-bit sums.
6029 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6030 LHS, RHS, DAG, dl, MVT::v8i16);
6031 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6033 // Multiply the odd 8-bit parts, producing 16-bit sums.
6034 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6035 LHS, RHS, DAG, dl, MVT::v8i16);
6036 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6038 // Merge the results together.
6040 for (unsigned i = 0; i != 8; ++i) {
6042 Ops[i*2+1] = 2*i+1+16;
6044 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6046 llvm_unreachable("Unknown mul to lower!");
6050 /// LowerOperation - Provide custom lowering hooks for some operations.
6052 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6053 switch (Op.getOpcode()) {
6054 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6055 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6056 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6057 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6058 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6059 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6060 case ISD::SETCC: return LowerSETCC(Op, DAG);
6061 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
6062 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
6064 return LowerVASTART(Op, DAG, PPCSubTarget);
6067 return LowerVAARG(Op, DAG, PPCSubTarget);
6070 return LowerVACOPY(Op, DAG, PPCSubTarget);
6072 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
6073 case ISD::DYNAMIC_STACKALLOC:
6074 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
6076 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
6077 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
6079 case ISD::LOAD: return LowerLOAD(Op, DAG);
6080 case ISD::STORE: return LowerSTORE(Op, DAG);
6081 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
6082 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6083 case ISD::FP_TO_UINT:
6084 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
6086 case ISD::UINT_TO_FP:
6087 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6088 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6090 // Lower 64-bit shifts.
6091 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
6092 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
6093 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
6095 // Vector-related lowering.
6096 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6097 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6098 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6099 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6100 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
6101 case ISD::MUL: return LowerMUL(Op, DAG);
6103 // For counter-based loop handling.
6104 case ISD::INTRINSIC_W_CHAIN: return SDValue();
6106 // Frame & Return address.
6107 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6108 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6112 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6113 SmallVectorImpl<SDValue>&Results,
6114 SelectionDAG &DAG) const {
6115 const TargetMachine &TM = getTargetMachine();
6117 switch (N->getOpcode()) {
6119 llvm_unreachable("Do not know how to custom type legalize this operation!");
6120 case ISD::INTRINSIC_W_CHAIN: {
6121 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6122 Intrinsic::ppc_is_decremented_ctr_nonzero)
6125 assert(N->getValueType(0) == MVT::i1 &&
6126 "Unexpected result type for CTR decrement intrinsic");
6127 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6128 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6129 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6132 Results.push_back(NewInt);
6133 Results.push_back(NewInt.getValue(1));
6137 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
6138 || TM.getSubtarget<PPCSubtarget>().isPPC64())
6141 EVT VT = N->getValueType(0);
6143 if (VT == MVT::i64) {
6144 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
6146 Results.push_back(NewNode);
6147 Results.push_back(NewNode.getValue(1));
6151 case ISD::FP_ROUND_INREG: {
6152 assert(N->getValueType(0) == MVT::ppcf128);
6153 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6154 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6155 MVT::f64, N->getOperand(0),
6156 DAG.getIntPtrConstant(0));
6157 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6158 MVT::f64, N->getOperand(0),
6159 DAG.getIntPtrConstant(1));
6161 // Add the two halves of the long double in round-to-zero mode.
6162 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6164 // We know the low half is about to be thrown away, so just use something
6166 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6170 case ISD::FP_TO_SINT:
6171 // LowerFP_TO_INT() can only handle f32 and f64.
6172 if (N->getOperand(0).getValueType() == MVT::ppcf128)
6174 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6180 //===----------------------------------------------------------------------===//
6181 // Other Lowering Code
6182 //===----------------------------------------------------------------------===//
6185 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6186 bool is64bit, unsigned BinOpcode) const {
6187 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6188 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6190 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6191 MachineFunction *F = BB->getParent();
6192 MachineFunction::iterator It = BB;
6195 unsigned dest = MI->getOperand(0).getReg();
6196 unsigned ptrA = MI->getOperand(1).getReg();
6197 unsigned ptrB = MI->getOperand(2).getReg();
6198 unsigned incr = MI->getOperand(3).getReg();
6199 DebugLoc dl = MI->getDebugLoc();
6201 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6202 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6203 F->insert(It, loopMBB);
6204 F->insert(It, exitMBB);
6205 exitMBB->splice(exitMBB->begin(), BB,
6206 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6207 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6209 MachineRegisterInfo &RegInfo = F->getRegInfo();
6210 unsigned TmpReg = (!BinOpcode) ? incr :
6211 RegInfo.createVirtualRegister(
6212 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6213 (const TargetRegisterClass *) &PPC::GPRCRegClass);
6217 // fallthrough --> loopMBB
6218 BB->addSuccessor(loopMBB);
6221 // l[wd]arx dest, ptr
6222 // add r0, dest, incr
6223 // st[wd]cx. r0, ptr
6225 // fallthrough --> exitMBB
6227 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6228 .addReg(ptrA).addReg(ptrB);
6230 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6231 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6232 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6233 BuildMI(BB, dl, TII->get(PPC::BCC))
6234 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6235 BB->addSuccessor(loopMBB);
6236 BB->addSuccessor(exitMBB);
6245 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6246 MachineBasicBlock *BB,
6247 bool is8bit, // operation
6248 unsigned BinOpcode) const {
6249 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6250 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6251 // In 64 bit mode we have to use 64 bits for addresses, even though the
6252 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
6253 // registers without caring whether they're 32 or 64, but here we're
6254 // doing actual arithmetic on the addresses.
6255 bool is64bit = PPCSubTarget.isPPC64();
6256 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6258 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6259 MachineFunction *F = BB->getParent();
6260 MachineFunction::iterator It = BB;
6263 unsigned dest = MI->getOperand(0).getReg();
6264 unsigned ptrA = MI->getOperand(1).getReg();
6265 unsigned ptrB = MI->getOperand(2).getReg();
6266 unsigned incr = MI->getOperand(3).getReg();
6267 DebugLoc dl = MI->getDebugLoc();
6269 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6270 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6271 F->insert(It, loopMBB);
6272 F->insert(It, exitMBB);
6273 exitMBB->splice(exitMBB->begin(), BB,
6274 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6275 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6277 MachineRegisterInfo &RegInfo = F->getRegInfo();
6278 const TargetRegisterClass *RC =
6279 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6280 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6281 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6282 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6283 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6284 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6285 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6286 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6287 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6288 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6289 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6290 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6291 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6293 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6297 // fallthrough --> loopMBB
6298 BB->addSuccessor(loopMBB);
6300 // The 4-byte load must be aligned, while a char or short may be
6301 // anywhere in the word. Hence all this nasty bookkeeping code.
6302 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6303 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6304 // xori shift, shift1, 24 [16]
6305 // rlwinm ptr, ptr1, 0, 0, 29
6306 // slw incr2, incr, shift
6307 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6308 // slw mask, mask2, shift
6310 // lwarx tmpDest, ptr
6311 // add tmp, tmpDest, incr2
6312 // andc tmp2, tmpDest, mask
6313 // and tmp3, tmp, mask
6314 // or tmp4, tmp3, tmp2
6317 // fallthrough --> exitMBB
6318 // srw dest, tmpDest, shift
6319 if (ptrA != ZeroReg) {
6320 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6321 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6322 .addReg(ptrA).addReg(ptrB);
6326 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6327 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6328 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6329 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6331 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6332 .addReg(Ptr1Reg).addImm(0).addImm(61);
6334 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6335 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6336 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6337 .addReg(incr).addReg(ShiftReg);
6339 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6341 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6342 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6344 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6345 .addReg(Mask2Reg).addReg(ShiftReg);
6348 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6349 .addReg(ZeroReg).addReg(PtrReg);
6351 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6352 .addReg(Incr2Reg).addReg(TmpDestReg);
6353 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6354 .addReg(TmpDestReg).addReg(MaskReg);
6355 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6356 .addReg(TmpReg).addReg(MaskReg);
6357 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6358 .addReg(Tmp3Reg).addReg(Tmp2Reg);
6359 BuildMI(BB, dl, TII->get(PPC::STWCX))
6360 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6361 BuildMI(BB, dl, TII->get(PPC::BCC))
6362 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6363 BB->addSuccessor(loopMBB);
6364 BB->addSuccessor(exitMBB);
6369 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6374 llvm::MachineBasicBlock*
6375 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6376 MachineBasicBlock *MBB) const {
6377 DebugLoc DL = MI->getDebugLoc();
6378 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6380 MachineFunction *MF = MBB->getParent();
6381 MachineRegisterInfo &MRI = MF->getRegInfo();
6383 const BasicBlock *BB = MBB->getBasicBlock();
6384 MachineFunction::iterator I = MBB;
6388 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6389 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6391 unsigned DstReg = MI->getOperand(0).getReg();
6392 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6393 assert(RC->hasType(MVT::i32) && "Invalid destination!");
6394 unsigned mainDstReg = MRI.createVirtualRegister(RC);
6395 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6397 MVT PVT = getPointerTy();
6398 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6399 "Invalid Pointer Size!");
6400 // For v = setjmp(buf), we generate
6403 // SjLjSetup mainMBB
6409 // buf[LabelOffset] = LR
6413 // v = phi(main, restore)
6416 MachineBasicBlock *thisMBB = MBB;
6417 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6418 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6419 MF->insert(I, mainMBB);
6420 MF->insert(I, sinkMBB);
6422 MachineInstrBuilder MIB;
6424 // Transfer the remainder of BB and its successor edges to sinkMBB.
6425 sinkMBB->splice(sinkMBB->begin(), MBB,
6426 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6427 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6429 // Note that the structure of the jmp_buf used here is not compatible
6430 // with that used by libc, and is not designed to be. Specifically, it
6431 // stores only those 'reserved' registers that LLVM does not otherwise
6432 // understand how to spill. Also, by convention, by the time this
6433 // intrinsic is called, Clang has already stored the frame address in the
6434 // first slot of the buffer and stack address in the third. Following the
6435 // X86 target code, we'll store the jump address in the second slot. We also
6436 // need to save the TOC pointer (R2) to handle jumps between shared
6437 // libraries, and that will be stored in the fourth slot. The thread
6438 // identifier (R13) is not affected.
6441 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6442 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6443 const int64_t BPOffset = 4 * PVT.getStoreSize();
6445 // Prepare IP either in reg.
6446 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6447 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6448 unsigned BufReg = MI->getOperand(1).getReg();
6450 if (PPCSubTarget.isPPC64() && PPCSubTarget.isSVR4ABI()) {
6451 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6455 MIB.setMemRefs(MMOBegin, MMOEnd);
6458 // Naked functions never have a base pointer, and so we use r1. For all
6459 // other functions, this decision must be delayed until during PEI.
6461 if (MF->getFunction()->getAttributes().hasAttribute(
6462 AttributeSet::FunctionIndex, Attribute::Naked))
6463 BaseReg = PPCSubTarget.isPPC64() ? PPC::X1 : PPC::R1;
6465 BaseReg = PPCSubTarget.isPPC64() ? PPC::BP8 : PPC::BP;
6467 MIB = BuildMI(*thisMBB, MI, DL,
6468 TII->get(PPCSubTarget.isPPC64() ? PPC::STD : PPC::STW))
6472 MIB.setMemRefs(MMOBegin, MMOEnd);
6475 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6476 const PPCRegisterInfo *TRI =
6477 static_cast<const PPCRegisterInfo*>(getTargetMachine().getRegisterInfo());
6478 MIB.addRegMask(TRI->getNoPreservedMask());
6480 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6482 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6484 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6486 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6487 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6491 MIB = BuildMI(mainMBB, DL,
6492 TII->get(PPCSubTarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6495 if (PPCSubTarget.isPPC64()) {
6496 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6498 .addImm(LabelOffset)
6501 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6503 .addImm(LabelOffset)
6507 MIB.setMemRefs(MMOBegin, MMOEnd);
6509 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6510 mainMBB->addSuccessor(sinkMBB);
6513 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6514 TII->get(PPC::PHI), DstReg)
6515 .addReg(mainDstReg).addMBB(mainMBB)
6516 .addReg(restoreDstReg).addMBB(thisMBB);
6518 MI->eraseFromParent();
6523 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6524 MachineBasicBlock *MBB) const {
6525 DebugLoc DL = MI->getDebugLoc();
6526 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6528 MachineFunction *MF = MBB->getParent();
6529 MachineRegisterInfo &MRI = MF->getRegInfo();
6532 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6533 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6535 MVT PVT = getPointerTy();
6536 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6537 "Invalid Pointer Size!");
6539 const TargetRegisterClass *RC =
6540 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6541 unsigned Tmp = MRI.createVirtualRegister(RC);
6542 // Since FP is only updated here but NOT referenced, it's treated as GPR.
6543 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6544 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6545 unsigned BP = (PVT == MVT::i64) ? PPC::X30 : PPC::R30;
6547 MachineInstrBuilder MIB;
6549 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6550 const int64_t SPOffset = 2 * PVT.getStoreSize();
6551 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6552 const int64_t BPOffset = 4 * PVT.getStoreSize();
6554 unsigned BufReg = MI->getOperand(0).getReg();
6556 // Reload FP (the jumped-to function may not have had a
6557 // frame pointer, and if so, then its r31 will be restored
6559 if (PVT == MVT::i64) {
6560 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6564 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6568 MIB.setMemRefs(MMOBegin, MMOEnd);
6571 if (PVT == MVT::i64) {
6572 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6573 .addImm(LabelOffset)
6576 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6577 .addImm(LabelOffset)
6580 MIB.setMemRefs(MMOBegin, MMOEnd);
6583 if (PVT == MVT::i64) {
6584 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6588 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6592 MIB.setMemRefs(MMOBegin, MMOEnd);
6595 if (PVT == MVT::i64) {
6596 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
6600 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
6604 MIB.setMemRefs(MMOBegin, MMOEnd);
6607 if (PVT == MVT::i64 && PPCSubTarget.isSVR4ABI()) {
6608 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6612 MIB.setMemRefs(MMOBegin, MMOEnd);
6616 BuildMI(*MBB, MI, DL,
6617 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6618 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6620 MI->eraseFromParent();
6625 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6626 MachineBasicBlock *BB) const {
6627 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6628 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6629 return emitEHSjLjSetJmp(MI, BB);
6630 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6631 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6632 return emitEHSjLjLongJmp(MI, BB);
6635 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6637 // To "insert" these instructions we actually have to insert their
6638 // control-flow patterns.
6639 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6640 MachineFunction::iterator It = BB;
6643 MachineFunction *F = BB->getParent();
6645 if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6646 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6647 MI->getOpcode() == PPC::SELECT_I4 ||
6648 MI->getOpcode() == PPC::SELECT_I8)) {
6649 SmallVector<MachineOperand, 2> Cond;
6650 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6651 MI->getOpcode() == PPC::SELECT_CC_I8)
6652 Cond.push_back(MI->getOperand(4));
6654 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
6655 Cond.push_back(MI->getOperand(1));
6657 DebugLoc dl = MI->getDebugLoc();
6658 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6659 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
6660 Cond, MI->getOperand(2).getReg(),
6661 MI->getOperand(3).getReg());
6662 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6663 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6664 MI->getOpcode() == PPC::SELECT_CC_F4 ||
6665 MI->getOpcode() == PPC::SELECT_CC_F8 ||
6666 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
6667 MI->getOpcode() == PPC::SELECT_I4 ||
6668 MI->getOpcode() == PPC::SELECT_I8 ||
6669 MI->getOpcode() == PPC::SELECT_F4 ||
6670 MI->getOpcode() == PPC::SELECT_F8 ||
6671 MI->getOpcode() == PPC::SELECT_VRRC) {
6672 // The incoming instruction knows the destination vreg to set, the
6673 // condition code register to branch on, the true/false values to
6674 // select between, and a branch opcode to use.
6679 // cmpTY ccX, r1, r2
6681 // fallthrough --> copy0MBB
6682 MachineBasicBlock *thisMBB = BB;
6683 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6684 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6685 DebugLoc dl = MI->getDebugLoc();
6686 F->insert(It, copy0MBB);
6687 F->insert(It, sinkMBB);
6689 // Transfer the remainder of BB and its successor edges to sinkMBB.
6690 sinkMBB->splice(sinkMBB->begin(), BB,
6691 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6692 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6694 // Next, add the true and fallthrough blocks as its successors.
6695 BB->addSuccessor(copy0MBB);
6696 BB->addSuccessor(sinkMBB);
6698 if (MI->getOpcode() == PPC::SELECT_I4 ||
6699 MI->getOpcode() == PPC::SELECT_I8 ||
6700 MI->getOpcode() == PPC::SELECT_F4 ||
6701 MI->getOpcode() == PPC::SELECT_F8 ||
6702 MI->getOpcode() == PPC::SELECT_VRRC) {
6703 BuildMI(BB, dl, TII->get(PPC::BC))
6704 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6706 unsigned SelectPred = MI->getOperand(4).getImm();
6707 BuildMI(BB, dl, TII->get(PPC::BCC))
6708 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6712 // %FalseValue = ...
6713 // # fallthrough to sinkMBB
6716 // Update machine-CFG edges
6717 BB->addSuccessor(sinkMBB);
6720 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6723 BuildMI(*BB, BB->begin(), dl,
6724 TII->get(PPC::PHI), MI->getOperand(0).getReg())
6725 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
6726 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6728 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
6729 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
6730 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
6731 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
6732 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
6733 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
6734 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
6735 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
6737 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
6738 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
6739 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
6740 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
6741 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
6742 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
6743 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
6744 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
6746 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
6747 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
6748 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
6749 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
6750 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
6751 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
6752 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
6753 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
6755 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
6756 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
6757 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
6758 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
6759 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
6760 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
6761 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
6762 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
6764 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
6765 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
6766 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
6767 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
6768 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
6769 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
6770 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
6771 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
6773 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
6774 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
6775 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
6776 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
6777 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
6778 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
6779 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
6780 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
6782 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
6783 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
6784 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
6785 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
6786 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
6787 BB = EmitAtomicBinary(MI, BB, false, 0);
6788 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
6789 BB = EmitAtomicBinary(MI, BB, true, 0);
6791 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
6792 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
6793 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
6795 unsigned dest = MI->getOperand(0).getReg();
6796 unsigned ptrA = MI->getOperand(1).getReg();
6797 unsigned ptrB = MI->getOperand(2).getReg();
6798 unsigned oldval = MI->getOperand(3).getReg();
6799 unsigned newval = MI->getOperand(4).getReg();
6800 DebugLoc dl = MI->getDebugLoc();
6802 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6803 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6804 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6805 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6806 F->insert(It, loop1MBB);
6807 F->insert(It, loop2MBB);
6808 F->insert(It, midMBB);
6809 F->insert(It, exitMBB);
6810 exitMBB->splice(exitMBB->begin(), BB,
6811 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6812 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6816 // fallthrough --> loopMBB
6817 BB->addSuccessor(loop1MBB);
6820 // l[wd]arx dest, ptr
6821 // cmp[wd] dest, oldval
6824 // st[wd]cx. newval, ptr
6828 // st[wd]cx. dest, ptr
6831 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6832 .addReg(ptrA).addReg(ptrB);
6833 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
6834 .addReg(oldval).addReg(dest);
6835 BuildMI(BB, dl, TII->get(PPC::BCC))
6836 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6837 BB->addSuccessor(loop2MBB);
6838 BB->addSuccessor(midMBB);
6841 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6842 .addReg(newval).addReg(ptrA).addReg(ptrB);
6843 BuildMI(BB, dl, TII->get(PPC::BCC))
6844 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6845 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6846 BB->addSuccessor(loop1MBB);
6847 BB->addSuccessor(exitMBB);
6850 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6851 .addReg(dest).addReg(ptrA).addReg(ptrB);
6852 BB->addSuccessor(exitMBB);
6857 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
6858 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
6859 // We must use 64-bit registers for addresses when targeting 64-bit,
6860 // since we're actually doing arithmetic on them. Other registers
6862 bool is64bit = PPCSubTarget.isPPC64();
6863 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
6865 unsigned dest = MI->getOperand(0).getReg();
6866 unsigned ptrA = MI->getOperand(1).getReg();
6867 unsigned ptrB = MI->getOperand(2).getReg();
6868 unsigned oldval = MI->getOperand(3).getReg();
6869 unsigned newval = MI->getOperand(4).getReg();
6870 DebugLoc dl = MI->getDebugLoc();
6872 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6873 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6874 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6875 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6876 F->insert(It, loop1MBB);
6877 F->insert(It, loop2MBB);
6878 F->insert(It, midMBB);
6879 F->insert(It, exitMBB);
6880 exitMBB->splice(exitMBB->begin(), BB,
6881 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6882 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6884 MachineRegisterInfo &RegInfo = F->getRegInfo();
6885 const TargetRegisterClass *RC =
6886 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6887 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6888 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6889 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6890 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6891 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
6892 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
6893 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
6894 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
6895 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6896 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6897 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6898 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6899 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6900 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6902 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
6903 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6906 // fallthrough --> loopMBB
6907 BB->addSuccessor(loop1MBB);
6909 // The 4-byte load must be aligned, while a char or short may be
6910 // anywhere in the word. Hence all this nasty bookkeeping code.
6911 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6912 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6913 // xori shift, shift1, 24 [16]
6914 // rlwinm ptr, ptr1, 0, 0, 29
6915 // slw newval2, newval, shift
6916 // slw oldval2, oldval,shift
6917 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6918 // slw mask, mask2, shift
6919 // and newval3, newval2, mask
6920 // and oldval3, oldval2, mask
6922 // lwarx tmpDest, ptr
6923 // and tmp, tmpDest, mask
6924 // cmpw tmp, oldval3
6927 // andc tmp2, tmpDest, mask
6928 // or tmp4, tmp2, newval3
6933 // stwcx. tmpDest, ptr
6935 // srw dest, tmpDest, shift
6936 if (ptrA != ZeroReg) {
6937 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6938 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6939 .addReg(ptrA).addReg(ptrB);
6943 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6944 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6945 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6946 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6948 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6949 .addReg(Ptr1Reg).addImm(0).addImm(61);
6951 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6952 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6953 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
6954 .addReg(newval).addReg(ShiftReg);
6955 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
6956 .addReg(oldval).addReg(ShiftReg);
6958 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6960 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6961 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
6962 .addReg(Mask3Reg).addImm(65535);
6964 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6965 .addReg(Mask2Reg).addReg(ShiftReg);
6966 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
6967 .addReg(NewVal2Reg).addReg(MaskReg);
6968 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
6969 .addReg(OldVal2Reg).addReg(MaskReg);
6972 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6973 .addReg(ZeroReg).addReg(PtrReg);
6974 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
6975 .addReg(TmpDestReg).addReg(MaskReg);
6976 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
6977 .addReg(TmpReg).addReg(OldVal3Reg);
6978 BuildMI(BB, dl, TII->get(PPC::BCC))
6979 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6980 BB->addSuccessor(loop2MBB);
6981 BB->addSuccessor(midMBB);
6984 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
6985 .addReg(TmpDestReg).addReg(MaskReg);
6986 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
6987 .addReg(Tmp2Reg).addReg(NewVal3Reg);
6988 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
6989 .addReg(ZeroReg).addReg(PtrReg);
6990 BuildMI(BB, dl, TII->get(PPC::BCC))
6991 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6992 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6993 BB->addSuccessor(loop1MBB);
6994 BB->addSuccessor(exitMBB);
6997 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
6998 .addReg(ZeroReg).addReg(PtrReg);
6999 BB->addSuccessor(exitMBB);
7004 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7006 } else if (MI->getOpcode() == PPC::FADDrtz) {
7007 // This pseudo performs an FADD with rounding mode temporarily forced
7008 // to round-to-zero. We emit this via custom inserter since the FPSCR
7009 // is not modeled at the SelectionDAG level.
7010 unsigned Dest = MI->getOperand(0).getReg();
7011 unsigned Src1 = MI->getOperand(1).getReg();
7012 unsigned Src2 = MI->getOperand(2).getReg();
7013 DebugLoc dl = MI->getDebugLoc();
7015 MachineRegisterInfo &RegInfo = F->getRegInfo();
7016 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7018 // Save FPSCR value.
7019 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7021 // Set rounding mode to round-to-zero.
7022 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7023 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7025 // Perform addition.
7026 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7028 // Restore FPSCR value.
7029 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
7030 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7031 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7032 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7033 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7034 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7035 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7036 PPC::ANDIo8 : PPC::ANDIo;
7037 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7038 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7040 MachineRegisterInfo &RegInfo = F->getRegInfo();
7041 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7042 &PPC::GPRCRegClass :
7043 &PPC::G8RCRegClass);
7045 DebugLoc dl = MI->getDebugLoc();
7046 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7047 .addReg(MI->getOperand(1).getReg()).addImm(1);
7048 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7049 MI->getOperand(0).getReg())
7050 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7052 llvm_unreachable("Unexpected instr type to insert");
7055 MI->eraseFromParent(); // The pseudo instruction is gone now.
7059 //===----------------------------------------------------------------------===//
7060 // Target Optimization Hooks
7061 //===----------------------------------------------------------------------===//
7063 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op,
7064 DAGCombinerInfo &DCI) const {
7065 if (DCI.isAfterLegalizeVectorOps())
7068 EVT VT = Op.getValueType();
7070 if ((VT == MVT::f32 && PPCSubTarget.hasFRES()) ||
7071 (VT == MVT::f64 && PPCSubTarget.hasFRE()) ||
7072 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec()) ||
7073 (VT == MVT::v2f64 && PPCSubTarget.hasVSX())) {
7075 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7076 // For the reciprocal, we need to find the zero of the function:
7077 // F(X) = A X - 1 [which has a zero at X = 1/A]
7079 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
7080 // does not require additional intermediate precision]
7082 // Convergence is quadratic, so we essentially double the number of digits
7083 // correct after every iteration. The minimum architected relative
7084 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7085 // 23 digits and double has 52 digits.
7086 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
7087 if (VT.getScalarType() == MVT::f64)
7090 SelectionDAG &DAG = DCI.DAG;
7094 DAG.getConstantFP(1.0, VT.getScalarType());
7095 if (VT.isVector()) {
7096 assert(VT.getVectorNumElements() == 4 &&
7097 "Unknown vector type");
7098 FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7099 FPOne, FPOne, FPOne, FPOne);
7102 SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op);
7103 DCI.AddToWorklist(Est.getNode());
7105 // Newton iterations: Est = Est + Est (1 - Arg * Est)
7106 for (int i = 0; i < Iterations; ++i) {
7107 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est);
7108 DCI.AddToWorklist(NewEst.getNode());
7110 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst);
7111 DCI.AddToWorklist(NewEst.getNode());
7113 NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7114 DCI.AddToWorklist(NewEst.getNode());
7116 Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst);
7117 DCI.AddToWorklist(Est.getNode());
7126 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op,
7127 DAGCombinerInfo &DCI) const {
7128 if (DCI.isAfterLegalizeVectorOps())
7131 EVT VT = Op.getValueType();
7133 if ((VT == MVT::f32 && PPCSubTarget.hasFRSQRTES()) ||
7134 (VT == MVT::f64 && PPCSubTarget.hasFRSQRTE()) ||
7135 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec()) ||
7136 (VT == MVT::v2f64 && PPCSubTarget.hasVSX())) {
7138 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7139 // For the reciprocal sqrt, we need to find the zero of the function:
7140 // F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
7142 // X_{i+1} = X_i (1.5 - A X_i^2 / 2)
7143 // As a result, we precompute A/2 prior to the iteration loop.
7145 // Convergence is quadratic, so we essentially double the number of digits
7146 // correct after every iteration. The minimum architected relative
7147 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7148 // 23 digits and double has 52 digits.
7149 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
7150 if (VT.getScalarType() == MVT::f64)
7153 SelectionDAG &DAG = DCI.DAG;
7156 SDValue FPThreeHalves =
7157 DAG.getConstantFP(1.5, VT.getScalarType());
7158 if (VT.isVector()) {
7159 assert(VT.getVectorNumElements() == 4 &&
7160 "Unknown vector type");
7161 FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7162 FPThreeHalves, FPThreeHalves,
7163 FPThreeHalves, FPThreeHalves);
7166 SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op);
7167 DCI.AddToWorklist(Est.getNode());
7169 // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that
7170 // this entire sequence requires only one FP constant.
7171 SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op);
7172 DCI.AddToWorklist(HalfArg.getNode());
7174 HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op);
7175 DCI.AddToWorklist(HalfArg.getNode());
7177 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
7178 for (int i = 0; i < Iterations; ++i) {
7179 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est);
7180 DCI.AddToWorklist(NewEst.getNode());
7182 NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst);
7183 DCI.AddToWorklist(NewEst.getNode());
7185 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst);
7186 DCI.AddToWorklist(NewEst.getNode());
7188 Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7189 DCI.AddToWorklist(Est.getNode());
7198 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7199 // not enforce equality of the chain operands.
7200 static bool isConsecutiveLS(LSBaseSDNode *LS, LSBaseSDNode *Base,
7201 unsigned Bytes, int Dist,
7202 SelectionDAG &DAG) {
7203 EVT VT = LS->getMemoryVT();
7204 if (VT.getSizeInBits() / 8 != Bytes)
7207 SDValue Loc = LS->getBasePtr();
7208 SDValue BaseLoc = Base->getBasePtr();
7209 if (Loc.getOpcode() == ISD::FrameIndex) {
7210 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7212 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7213 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7214 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7215 int FS = MFI->getObjectSize(FI);
7216 int BFS = MFI->getObjectSize(BFI);
7217 if (FS != BFS || FS != (int)Bytes) return false;
7218 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7222 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7223 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7226 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7227 const GlobalValue *GV1 = nullptr;
7228 const GlobalValue *GV2 = nullptr;
7229 int64_t Offset1 = 0;
7230 int64_t Offset2 = 0;
7231 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7232 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7233 if (isGA1 && isGA2 && GV1 == GV2)
7234 return Offset1 == (Offset2 + Dist*Bytes);
7238 // Return true is there is a nearyby consecutive load to the one provided
7239 // (regardless of alignment). We search up and down the chain, looking though
7240 // token factors and other loads (but nothing else). As a result, a true
7241 // results indicates that it is safe to create a new consecutive load adjacent
7242 // to the load provided.
7243 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7244 SDValue Chain = LD->getChain();
7245 EVT VT = LD->getMemoryVT();
7247 SmallSet<SDNode *, 16> LoadRoots;
7248 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7249 SmallSet<SDNode *, 16> Visited;
7251 // First, search up the chain, branching to follow all token-factor operands.
7252 // If we find a consecutive load, then we're done, otherwise, record all
7253 // nodes just above the top-level loads and token factors.
7254 while (!Queue.empty()) {
7255 SDNode *ChainNext = Queue.pop_back_val();
7256 if (!Visited.insert(ChainNext))
7259 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(ChainNext)) {
7260 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7263 if (!Visited.count(ChainLD->getChain().getNode()))
7264 Queue.push_back(ChainLD->getChain().getNode());
7265 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7266 for (SDNode::op_iterator O = ChainNext->op_begin(),
7267 OE = ChainNext->op_end(); O != OE; ++O)
7268 if (!Visited.count(O->getNode()))
7269 Queue.push_back(O->getNode());
7271 LoadRoots.insert(ChainNext);
7274 // Second, search down the chain, starting from the top-level nodes recorded
7275 // in the first phase. These top-level nodes are the nodes just above all
7276 // loads and token factors. Starting with their uses, recursively look though
7277 // all loads (just the chain uses) and token factors to find a consecutive
7282 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7283 IE = LoadRoots.end(); I != IE; ++I) {
7284 Queue.push_back(*I);
7286 while (!Queue.empty()) {
7287 SDNode *LoadRoot = Queue.pop_back_val();
7288 if (!Visited.insert(LoadRoot))
7291 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(LoadRoot))
7292 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7295 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7296 UE = LoadRoot->use_end(); UI != UE; ++UI)
7297 if (((isa<LoadSDNode>(*UI) &&
7298 cast<LoadSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7299 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7300 Queue.push_back(*UI);
7307 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7308 DAGCombinerInfo &DCI) const {
7309 SelectionDAG &DAG = DCI.DAG;
7312 assert(PPCSubTarget.useCRBits() &&
7313 "Expecting to be tracking CR bits");
7314 // If we're tracking CR bits, we need to be careful that we don't have:
7315 // trunc(binary-ops(zext(x), zext(y)))
7317 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7318 // such that we're unnecessarily moving things into GPRs when it would be
7319 // better to keep them in CR bits.
7321 // Note that trunc here can be an actual i1 trunc, or can be the effective
7322 // truncation that comes from a setcc or select_cc.
7323 if (N->getOpcode() == ISD::TRUNCATE &&
7324 N->getValueType(0) != MVT::i1)
7327 if (N->getOperand(0).getValueType() != MVT::i32 &&
7328 N->getOperand(0).getValueType() != MVT::i64)
7331 if (N->getOpcode() == ISD::SETCC ||
7332 N->getOpcode() == ISD::SELECT_CC) {
7333 // If we're looking at a comparison, then we need to make sure that the
7334 // high bits (all except for the first) don't matter the result.
7336 cast<CondCodeSDNode>(N->getOperand(
7337 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7338 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7340 if (ISD::isSignedIntSetCC(CC)) {
7341 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7342 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7344 } else if (ISD::isUnsignedIntSetCC(CC)) {
7345 if (!DAG.MaskedValueIsZero(N->getOperand(0),
7346 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7347 !DAG.MaskedValueIsZero(N->getOperand(1),
7348 APInt::getHighBitsSet(OpBits, OpBits-1)))
7351 // This is neither a signed nor an unsigned comparison, just make sure
7352 // that the high bits are equal.
7353 APInt Op1Zero, Op1One;
7354 APInt Op2Zero, Op2One;
7355 DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
7356 DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
7358 // We don't really care about what is known about the first bit (if
7359 // anything), so clear it in all masks prior to comparing them.
7360 Op1Zero.clearBit(0); Op1One.clearBit(0);
7361 Op2Zero.clearBit(0); Op2One.clearBit(0);
7363 if (Op1Zero != Op2Zero || Op1One != Op2One)
7368 // We now know that the higher-order bits are irrelevant, we just need to
7369 // make sure that all of the intermediate operations are bit operations, and
7370 // all inputs are extensions.
7371 if (N->getOperand(0).getOpcode() != ISD::AND &&
7372 N->getOperand(0).getOpcode() != ISD::OR &&
7373 N->getOperand(0).getOpcode() != ISD::XOR &&
7374 N->getOperand(0).getOpcode() != ISD::SELECT &&
7375 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7376 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7377 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7378 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7379 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7382 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7383 N->getOperand(1).getOpcode() != ISD::AND &&
7384 N->getOperand(1).getOpcode() != ISD::OR &&
7385 N->getOperand(1).getOpcode() != ISD::XOR &&
7386 N->getOperand(1).getOpcode() != ISD::SELECT &&
7387 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7388 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7389 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7390 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7391 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7394 SmallVector<SDValue, 4> Inputs;
7395 SmallVector<SDValue, 8> BinOps, PromOps;
7396 SmallPtrSet<SDNode *, 16> Visited;
7398 for (unsigned i = 0; i < 2; ++i) {
7399 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7400 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7401 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7402 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7403 isa<ConstantSDNode>(N->getOperand(i)))
7404 Inputs.push_back(N->getOperand(i));
7406 BinOps.push_back(N->getOperand(i));
7408 if (N->getOpcode() == ISD::TRUNCATE)
7412 // Visit all inputs, collect all binary operations (and, or, xor and
7413 // select) that are all fed by extensions.
7414 while (!BinOps.empty()) {
7415 SDValue BinOp = BinOps.back();
7418 if (!Visited.insert(BinOp.getNode()))
7421 PromOps.push_back(BinOp);
7423 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7424 // The condition of the select is not promoted.
7425 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7427 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7430 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7431 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7432 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7433 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7434 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7435 Inputs.push_back(BinOp.getOperand(i));
7436 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7437 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7438 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7439 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7440 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
7441 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7442 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7443 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7444 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
7445 BinOps.push_back(BinOp.getOperand(i));
7447 // We have an input that is not an extension or another binary
7448 // operation; we'll abort this transformation.
7454 // Make sure that this is a self-contained cluster of operations (which
7455 // is not quite the same thing as saying that everything has only one
7457 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7458 if (isa<ConstantSDNode>(Inputs[i]))
7461 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7462 UE = Inputs[i].getNode()->use_end();
7465 if (User != N && !Visited.count(User))
7468 // Make sure that we're not going to promote the non-output-value
7469 // operand(s) or SELECT or SELECT_CC.
7470 // FIXME: Although we could sometimes handle this, and it does occur in
7471 // practice that one of the condition inputs to the select is also one of
7472 // the outputs, we currently can't deal with this.
7473 if (User->getOpcode() == ISD::SELECT) {
7474 if (User->getOperand(0) == Inputs[i])
7476 } else if (User->getOpcode() == ISD::SELECT_CC) {
7477 if (User->getOperand(0) == Inputs[i] ||
7478 User->getOperand(1) == Inputs[i])
7484 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7485 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7486 UE = PromOps[i].getNode()->use_end();
7489 if (User != N && !Visited.count(User))
7492 // Make sure that we're not going to promote the non-output-value
7493 // operand(s) or SELECT or SELECT_CC.
7494 // FIXME: Although we could sometimes handle this, and it does occur in
7495 // practice that one of the condition inputs to the select is also one of
7496 // the outputs, we currently can't deal with this.
7497 if (User->getOpcode() == ISD::SELECT) {
7498 if (User->getOperand(0) == PromOps[i])
7500 } else if (User->getOpcode() == ISD::SELECT_CC) {
7501 if (User->getOperand(0) == PromOps[i] ||
7502 User->getOperand(1) == PromOps[i])
7508 // Replace all inputs with the extension operand.
7509 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7510 // Constants may have users outside the cluster of to-be-promoted nodes,
7511 // and so we need to replace those as we do the promotions.
7512 if (isa<ConstantSDNode>(Inputs[i]))
7515 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
7518 // Replace all operations (these are all the same, but have a different
7519 // (i1) return type). DAG.getNode will validate that the types of
7520 // a binary operator match, so go through the list in reverse so that
7521 // we've likely promoted both operands first. Any intermediate truncations or
7522 // extensions disappear.
7523 while (!PromOps.empty()) {
7524 SDValue PromOp = PromOps.back();
7527 if (PromOp.getOpcode() == ISD::TRUNCATE ||
7528 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
7529 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
7530 PromOp.getOpcode() == ISD::ANY_EXTEND) {
7531 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
7532 PromOp.getOperand(0).getValueType() != MVT::i1) {
7533 // The operand is not yet ready (see comment below).
7534 PromOps.insert(PromOps.begin(), PromOp);
7538 SDValue RepValue = PromOp.getOperand(0);
7539 if (isa<ConstantSDNode>(RepValue))
7540 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
7542 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
7547 switch (PromOp.getOpcode()) {
7548 default: C = 0; break;
7549 case ISD::SELECT: C = 1; break;
7550 case ISD::SELECT_CC: C = 2; break;
7553 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7554 PromOp.getOperand(C).getValueType() != MVT::i1) ||
7555 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7556 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
7557 // The to-be-promoted operands of this node have not yet been
7558 // promoted (this should be rare because we're going through the
7559 // list backward, but if one of the operands has several users in
7560 // this cluster of to-be-promoted nodes, it is possible).
7561 PromOps.insert(PromOps.begin(), PromOp);
7565 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7566 PromOp.getNode()->op_end());
7568 // If there are any constant inputs, make sure they're replaced now.
7569 for (unsigned i = 0; i < 2; ++i)
7570 if (isa<ConstantSDNode>(Ops[C+i]))
7571 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
7573 DAG.ReplaceAllUsesOfValueWith(PromOp,
7574 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
7577 // Now we're left with the initial truncation itself.
7578 if (N->getOpcode() == ISD::TRUNCATE)
7579 return N->getOperand(0);
7581 // Otherwise, this is a comparison. The operands to be compared have just
7582 // changed type (to i1), but everything else is the same.
7583 return SDValue(N, 0);
7586 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
7587 DAGCombinerInfo &DCI) const {
7588 SelectionDAG &DAG = DCI.DAG;
7591 // If we're tracking CR bits, we need to be careful that we don't have:
7592 // zext(binary-ops(trunc(x), trunc(y)))
7594 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
7595 // such that we're unnecessarily moving things into CR bits that can more
7596 // efficiently stay in GPRs. Note that if we're not certain that the high
7597 // bits are set as required by the final extension, we still may need to do
7598 // some masking to get the proper behavior.
7600 // This same functionality is important on PPC64 when dealing with
7601 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
7602 // the return values of functions. Because it is so similar, it is handled
7605 if (N->getValueType(0) != MVT::i32 &&
7606 N->getValueType(0) != MVT::i64)
7609 if (!((N->getOperand(0).getValueType() == MVT::i1 &&
7610 PPCSubTarget.useCRBits()) ||
7611 (N->getOperand(0).getValueType() == MVT::i32 &&
7612 PPCSubTarget.isPPC64())))
7615 if (N->getOperand(0).getOpcode() != ISD::AND &&
7616 N->getOperand(0).getOpcode() != ISD::OR &&
7617 N->getOperand(0).getOpcode() != ISD::XOR &&
7618 N->getOperand(0).getOpcode() != ISD::SELECT &&
7619 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
7622 SmallVector<SDValue, 4> Inputs;
7623 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
7624 SmallPtrSet<SDNode *, 16> Visited;
7626 // Visit all inputs, collect all binary operations (and, or, xor and
7627 // select) that are all fed by truncations.
7628 while (!BinOps.empty()) {
7629 SDValue BinOp = BinOps.back();
7632 if (!Visited.insert(BinOp.getNode()))
7635 PromOps.push_back(BinOp);
7637 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7638 // The condition of the select is not promoted.
7639 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7641 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7644 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7645 isa<ConstantSDNode>(BinOp.getOperand(i))) {
7646 Inputs.push_back(BinOp.getOperand(i));
7647 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7648 BinOp.getOperand(i).getOpcode() == ISD::OR ||
7649 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7650 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7651 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
7652 BinOps.push_back(BinOp.getOperand(i));
7654 // We have an input that is not a truncation or another binary
7655 // operation; we'll abort this transformation.
7661 // Make sure that this is a self-contained cluster of operations (which
7662 // is not quite the same thing as saying that everything has only one
7664 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7665 if (isa<ConstantSDNode>(Inputs[i]))
7668 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7669 UE = Inputs[i].getNode()->use_end();
7672 if (User != N && !Visited.count(User))
7675 // Make sure that we're not going to promote the non-output-value
7676 // operand(s) or SELECT or SELECT_CC.
7677 // FIXME: Although we could sometimes handle this, and it does occur in
7678 // practice that one of the condition inputs to the select is also one of
7679 // the outputs, we currently can't deal with this.
7680 if (User->getOpcode() == ISD::SELECT) {
7681 if (User->getOperand(0) == Inputs[i])
7683 } else if (User->getOpcode() == ISD::SELECT_CC) {
7684 if (User->getOperand(0) == Inputs[i] ||
7685 User->getOperand(1) == Inputs[i])
7691 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7692 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7693 UE = PromOps[i].getNode()->use_end();
7696 if (User != N && !Visited.count(User))
7699 // Make sure that we're not going to promote the non-output-value
7700 // operand(s) or SELECT or SELECT_CC.
7701 // FIXME: Although we could sometimes handle this, and it does occur in
7702 // practice that one of the condition inputs to the select is also one of
7703 // the outputs, we currently can't deal with this.
7704 if (User->getOpcode() == ISD::SELECT) {
7705 if (User->getOperand(0) == PromOps[i])
7707 } else if (User->getOpcode() == ISD::SELECT_CC) {
7708 if (User->getOperand(0) == PromOps[i] ||
7709 User->getOperand(1) == PromOps[i])
7715 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
7716 bool ReallyNeedsExt = false;
7717 if (N->getOpcode() != ISD::ANY_EXTEND) {
7718 // If all of the inputs are not already sign/zero extended, then
7719 // we'll still need to do that at the end.
7720 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7721 if (isa<ConstantSDNode>(Inputs[i]))
7725 Inputs[i].getOperand(0).getValueSizeInBits();
7726 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
7728 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
7729 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
7730 APInt::getHighBitsSet(OpBits,
7731 OpBits-PromBits))) ||
7732 (N->getOpcode() == ISD::SIGN_EXTEND &&
7733 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
7734 (OpBits-(PromBits-1)))) {
7735 ReallyNeedsExt = true;
7741 // Replace all inputs, either with the truncation operand, or a
7742 // truncation or extension to the final output type.
7743 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7744 // Constant inputs need to be replaced with the to-be-promoted nodes that
7745 // use them because they might have users outside of the cluster of
7747 if (isa<ConstantSDNode>(Inputs[i]))
7750 SDValue InSrc = Inputs[i].getOperand(0);
7751 if (Inputs[i].getValueType() == N->getValueType(0))
7752 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
7753 else if (N->getOpcode() == ISD::SIGN_EXTEND)
7754 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7755 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
7756 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7757 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7758 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
7760 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7761 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
7764 // Replace all operations (these are all the same, but have a different
7765 // (promoted) return type). DAG.getNode will validate that the types of
7766 // a binary operator match, so go through the list in reverse so that
7767 // we've likely promoted both operands first.
7768 while (!PromOps.empty()) {
7769 SDValue PromOp = PromOps.back();
7773 switch (PromOp.getOpcode()) {
7774 default: C = 0; break;
7775 case ISD::SELECT: C = 1; break;
7776 case ISD::SELECT_CC: C = 2; break;
7779 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7780 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
7781 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7782 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
7783 // The to-be-promoted operands of this node have not yet been
7784 // promoted (this should be rare because we're going through the
7785 // list backward, but if one of the operands has several users in
7786 // this cluster of to-be-promoted nodes, it is possible).
7787 PromOps.insert(PromOps.begin(), PromOp);
7791 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7792 PromOp.getNode()->op_end());
7794 // If this node has constant inputs, then they'll need to be promoted here.
7795 for (unsigned i = 0; i < 2; ++i) {
7796 if (!isa<ConstantSDNode>(Ops[C+i]))
7798 if (Ops[C+i].getValueType() == N->getValueType(0))
7801 if (N->getOpcode() == ISD::SIGN_EXTEND)
7802 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7803 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7804 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7806 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7809 DAG.ReplaceAllUsesOfValueWith(PromOp,
7810 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
7813 // Now we're left with the initial extension itself.
7814 if (!ReallyNeedsExt)
7815 return N->getOperand(0);
7817 // To zero extend, just mask off everything except for the first bit (in the
7819 if (N->getOpcode() == ISD::ZERO_EXTEND)
7820 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
7821 DAG.getConstant(APInt::getLowBitsSet(
7822 N->getValueSizeInBits(0), PromBits),
7823 N->getValueType(0)));
7825 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
7826 "Invalid extension type");
7827 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
7829 DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
7830 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
7831 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
7832 N->getOperand(0), ShiftCst), ShiftCst);
7835 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
7836 DAGCombinerInfo &DCI) const {
7837 const TargetMachine &TM = getTargetMachine();
7838 SelectionDAG &DAG = DCI.DAG;
7840 switch (N->getOpcode()) {
7843 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7844 if (C->isNullValue()) // 0 << V -> 0.
7845 return N->getOperand(0);
7849 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7850 if (C->isNullValue()) // 0 >>u V -> 0.
7851 return N->getOperand(0);
7855 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7856 if (C->isNullValue() || // 0 >>s V -> 0.
7857 C->isAllOnesValue()) // -1 >>s V -> -1.
7858 return N->getOperand(0);
7861 case ISD::SIGN_EXTEND:
7862 case ISD::ZERO_EXTEND:
7863 case ISD::ANY_EXTEND:
7864 return DAGCombineExtBoolTrunc(N, DCI);
7867 case ISD::SELECT_CC:
7868 return DAGCombineTruncBoolExt(N, DCI);
7870 assert(TM.Options.UnsafeFPMath &&
7871 "Reciprocal estimates require UnsafeFPMath");
7873 if (N->getOperand(1).getOpcode() == ISD::FSQRT) {
7875 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI);
7877 DCI.AddToWorklist(RV.getNode());
7878 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7879 N->getOperand(0), RV);
7881 } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND &&
7882 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7884 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7887 DCI.AddToWorklist(RV.getNode());
7888 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N->getOperand(1)),
7889 N->getValueType(0), RV);
7890 DCI.AddToWorklist(RV.getNode());
7891 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7892 N->getOperand(0), RV);
7894 } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND &&
7895 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7897 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7900 DCI.AddToWorklist(RV.getNode());
7901 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N->getOperand(1)),
7902 N->getValueType(0), RV,
7903 N->getOperand(1).getOperand(1));
7904 DCI.AddToWorklist(RV.getNode());
7905 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7906 N->getOperand(0), RV);
7910 SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI);
7912 DCI.AddToWorklist(RV.getNode());
7913 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7914 N->getOperand(0), RV);
7920 assert(TM.Options.UnsafeFPMath &&
7921 "Reciprocal estimates require UnsafeFPMath");
7923 // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the
7925 SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI);
7927 DCI.AddToWorklist(RV.getNode());
7928 RV = DAGCombineFastRecip(RV, DCI);
7930 // Unfortunately, RV is now NaN if the input was exactly 0. Select out
7931 // this case and force the answer to 0.
7933 EVT VT = RV.getValueType();
7935 SDValue Zero = DAG.getConstantFP(0.0, VT.getScalarType());
7936 if (VT.isVector()) {
7937 assert(VT.getVectorNumElements() == 4 && "Unknown vector type");
7938 Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Zero, Zero, Zero, Zero);
7942 DAG.getSetCC(dl, getSetCCResultType(*DAG.getContext(), VT),
7943 N->getOperand(0), Zero, ISD::SETEQ);
7944 DCI.AddToWorklist(ZeroCmp.getNode());
7945 DCI.AddToWorklist(RV.getNode());
7947 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, dl, VT,
7955 case ISD::SINT_TO_FP:
7956 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
7957 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
7958 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
7959 // We allow the src/dst to be either f32/f64, but the intermediate
7960 // type must be i64.
7961 if (N->getOperand(0).getValueType() == MVT::i64 &&
7962 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
7963 SDValue Val = N->getOperand(0).getOperand(0);
7964 if (Val.getValueType() == MVT::f32) {
7965 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7966 DCI.AddToWorklist(Val.getNode());
7969 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
7970 DCI.AddToWorklist(Val.getNode());
7971 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
7972 DCI.AddToWorklist(Val.getNode());
7973 if (N->getValueType(0) == MVT::f32) {
7974 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
7975 DAG.getIntPtrConstant(0));
7976 DCI.AddToWorklist(Val.getNode());
7979 } else if (N->getOperand(0).getValueType() == MVT::i32) {
7980 // If the intermediate type is i32, we can avoid the load/store here
7987 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
7988 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
7989 !cast<StoreSDNode>(N)->isTruncatingStore() &&
7990 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
7991 N->getOperand(1).getValueType() == MVT::i32 &&
7992 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
7993 SDValue Val = N->getOperand(1).getOperand(0);
7994 if (Val.getValueType() == MVT::f32) {
7995 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7996 DCI.AddToWorklist(Val.getNode());
7998 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
7999 DCI.AddToWorklist(Val.getNode());
8002 N->getOperand(0), Val, N->getOperand(2),
8003 DAG.getValueType(N->getOperand(1).getValueType())
8006 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8007 DAG.getVTList(MVT::Other), Ops,
8008 cast<StoreSDNode>(N)->getMemoryVT(),
8009 cast<StoreSDNode>(N)->getMemOperand());
8010 DCI.AddToWorklist(Val.getNode());
8014 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8015 if (cast<StoreSDNode>(N)->isUnindexed() &&
8016 N->getOperand(1).getOpcode() == ISD::BSWAP &&
8017 N->getOperand(1).getNode()->hasOneUse() &&
8018 (N->getOperand(1).getValueType() == MVT::i32 ||
8019 N->getOperand(1).getValueType() == MVT::i16 ||
8020 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8021 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8022 N->getOperand(1).getValueType() == MVT::i64))) {
8023 SDValue BSwapOp = N->getOperand(1).getOperand(0);
8024 // Do an any-extend to 32-bits if this is a half-word input.
8025 if (BSwapOp.getValueType() == MVT::i16)
8026 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8029 N->getOperand(0), BSwapOp, N->getOperand(2),
8030 DAG.getValueType(N->getOperand(1).getValueType())
8033 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8034 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
8035 cast<StoreSDNode>(N)->getMemOperand());
8039 LoadSDNode *LD = cast<LoadSDNode>(N);
8040 EVT VT = LD->getValueType(0);
8041 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8042 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8043 if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
8044 TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
8045 (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8046 VT == MVT::v4i32 || VT == MVT::v4f32) &&
8047 LD->getAlignment() < ABIAlignment) {
8048 // This is a type-legal unaligned Altivec load.
8049 SDValue Chain = LD->getChain();
8050 SDValue Ptr = LD->getBasePtr();
8052 // This implements the loading of unaligned vectors as described in
8053 // the venerable Apple Velocity Engine overview. Specifically:
8054 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8055 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8057 // The general idea is to expand a sequence of one or more unaligned
8058 // loads into a alignment-based permutation-control instruction (lvsl),
8059 // a series of regular vector loads (which always truncate their
8060 // input address to an aligned address), and a series of permutations.
8061 // The results of these permutations are the requested loaded values.
8062 // The trick is that the last "extra" load is not taken from the address
8063 // you might suspect (sizeof(vector) bytes after the last requested
8064 // load), but rather sizeof(vector) - 1 bytes after the last
8065 // requested vector. The point of this is to avoid a page fault if the
8066 // base address happened to be aligned. This works because if the base
8067 // address is aligned, then adding less than a full vector length will
8068 // cause the last vector in the sequence to be (re)loaded. Otherwise,
8069 // the next vector will be fetched as you might suspect was necessary.
8071 // We might be able to reuse the permutation generation from
8072 // a different base address offset from this one by an aligned amount.
8073 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8074 // optimization later.
8075 SDValue PermCntl = BuildIntrinsicOp(Intrinsic::ppc_altivec_lvsl, Ptr,
8076 DAG, dl, MVT::v16i8);
8078 // Refine the alignment of the original load (a "new" load created here
8079 // which was identical to the first except for the alignment would be
8080 // merged with the existing node regardless).
8081 MachineFunction &MF = DAG.getMachineFunction();
8082 MachineMemOperand *MMO =
8083 MF.getMachineMemOperand(LD->getPointerInfo(),
8084 LD->getMemOperand()->getFlags(),
8085 LD->getMemoryVT().getStoreSize(),
8087 LD->refineAlignment(MMO);
8088 SDValue BaseLoad = SDValue(LD, 0);
8090 // Note that the value of IncOffset (which is provided to the next
8091 // load's pointer info offset value, and thus used to calculate the
8092 // alignment), and the value of IncValue (which is actually used to
8093 // increment the pointer value) are different! This is because we
8094 // require the next load to appear to be aligned, even though it
8095 // is actually offset from the base pointer by a lesser amount.
8096 int IncOffset = VT.getSizeInBits() / 8;
8097 int IncValue = IncOffset;
8099 // Walk (both up and down) the chain looking for another load at the real
8100 // (aligned) offset (the alignment of the other load does not matter in
8101 // this case). If found, then do not use the offset reduction trick, as
8102 // that will prevent the loads from being later combined (as they would
8103 // otherwise be duplicates).
8104 if (!findConsecutiveLoad(LD, DAG))
8107 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
8108 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
8111 DAG.getLoad(VT, dl, Chain, Ptr,
8112 LD->getPointerInfo().getWithOffset(IncOffset),
8113 LD->isVolatile(), LD->isNonTemporal(),
8114 LD->isInvariant(), ABIAlignment);
8116 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8117 BaseLoad.getValue(1), ExtraLoad.getValue(1));
8119 if (BaseLoad.getValueType() != MVT::v4i32)
8120 BaseLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, BaseLoad);
8122 if (ExtraLoad.getValueType() != MVT::v4i32)
8123 ExtraLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, ExtraLoad);
8125 SDValue Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8126 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
8128 if (VT != MVT::v4i32)
8129 Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
8131 // Now we need to be really careful about how we update the users of the
8132 // original load. We cannot just call DCI.CombineTo (or
8133 // DAG.ReplaceAllUsesWith for that matter), because the load still has
8134 // uses created here (the permutation for example) that need to stay.
8135 SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
8137 SDUse &Use = UI.getUse();
8139 // Note: BaseLoad is checked here because it might not be N, but a
8141 if (User == Perm.getNode() || User == BaseLoad.getNode() ||
8142 User == TF.getNode() || Use.getResNo() > 1) {
8147 SDValue To = Use.getResNo() ? TF : Perm;
8150 SmallVector<SDValue, 8> Ops;
8151 for (SDNode::op_iterator O = User->op_begin(),
8152 OE = User->op_end(); O != OE; ++O) {
8159 DAG.UpdateNodeOperands(User, Ops);
8162 return SDValue(N, 0);
8166 case ISD::INTRINSIC_WO_CHAIN:
8167 if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() ==
8168 Intrinsic::ppc_altivec_lvsl &&
8169 N->getOperand(1)->getOpcode() == ISD::ADD) {
8170 SDValue Add = N->getOperand(1);
8172 if (DAG.MaskedValueIsZero(Add->getOperand(1),
8173 APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8174 Add.getValueType().getScalarType().getSizeInBits()))) {
8175 SDNode *BasePtr = Add->getOperand(0).getNode();
8176 for (SDNode::use_iterator UI = BasePtr->use_begin(),
8177 UE = BasePtr->use_end(); UI != UE; ++UI) {
8178 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8179 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8180 Intrinsic::ppc_altivec_lvsl) {
8181 // We've found another LVSL, and this address if an aligned
8182 // multiple of that one. The results will be the same, so use the
8183 // one we've just found instead.
8185 return SDValue(*UI, 0);
8193 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8194 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8195 N->getOperand(0).hasOneUse() &&
8196 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8197 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8198 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8199 N->getValueType(0) == MVT::i64))) {
8200 SDValue Load = N->getOperand(0);
8201 LoadSDNode *LD = cast<LoadSDNode>(Load);
8202 // Create the byte-swapping load.
8204 LD->getChain(), // Chain
8205 LD->getBasePtr(), // Ptr
8206 DAG.getValueType(N->getValueType(0)) // VT
8209 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8210 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8211 MVT::i64 : MVT::i32, MVT::Other),
8212 Ops, LD->getMemoryVT(), LD->getMemOperand());
8214 // If this is an i16 load, insert the truncate.
8215 SDValue ResVal = BSLoad;
8216 if (N->getValueType(0) == MVT::i16)
8217 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8219 // First, combine the bswap away. This makes the value produced by the
8221 DCI.CombineTo(N, ResVal);
8223 // Next, combine the load away, we give it a bogus result value but a real
8224 // chain result. The result value is dead because the bswap is dead.
8225 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8227 // Return N so it doesn't get rechecked!
8228 return SDValue(N, 0);
8232 case PPCISD::VCMP: {
8233 // If a VCMPo node already exists with exactly the same operands as this
8234 // node, use its result instead of this node (VCMPo computes both a CR6 and
8235 // a normal output).
8237 if (!N->getOperand(0).hasOneUse() &&
8238 !N->getOperand(1).hasOneUse() &&
8239 !N->getOperand(2).hasOneUse()) {
8241 // Scan all of the users of the LHS, looking for VCMPo's that match.
8242 SDNode *VCMPoNode = nullptr;
8244 SDNode *LHSN = N->getOperand(0).getNode();
8245 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8247 if (UI->getOpcode() == PPCISD::VCMPo &&
8248 UI->getOperand(1) == N->getOperand(1) &&
8249 UI->getOperand(2) == N->getOperand(2) &&
8250 UI->getOperand(0) == N->getOperand(0)) {
8255 // If there is no VCMPo node, or if the flag value has a single use, don't
8257 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8260 // Look at the (necessarily single) use of the flag value. If it has a
8261 // chain, this transformation is more complex. Note that multiple things
8262 // could use the value result, which we should ignore.
8263 SDNode *FlagUser = nullptr;
8264 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8265 FlagUser == nullptr; ++UI) {
8266 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8268 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8269 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8276 // If the user is a MFOCRF instruction, we know this is safe.
8277 // Otherwise we give up for right now.
8278 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
8279 return SDValue(VCMPoNode, 0);
8284 SDValue Cond = N->getOperand(1);
8285 SDValue Target = N->getOperand(2);
8287 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8288 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
8289 Intrinsic::ppc_is_decremented_ctr_nonzero) {
8291 // We now need to make the intrinsic dead (it cannot be instruction
8293 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
8294 assert(Cond.getNode()->hasOneUse() &&
8295 "Counter decrement has more than one use");
8297 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
8298 N->getOperand(0), Target);
8303 // If this is a branch on an altivec predicate comparison, lower this so
8304 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
8305 // lowering is done pre-legalize, because the legalizer lowers the predicate
8306 // compare down to code that is difficult to reassemble.
8307 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
8308 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
8310 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
8311 // value. If so, pass-through the AND to get to the intrinsic.
8312 if (LHS.getOpcode() == ISD::AND &&
8313 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8314 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
8315 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8316 isa<ConstantSDNode>(LHS.getOperand(1)) &&
8317 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
8319 LHS = LHS.getOperand(0);
8321 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8322 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
8323 Intrinsic::ppc_is_decremented_ctr_nonzero &&
8324 isa<ConstantSDNode>(RHS)) {
8325 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8326 "Counter decrement comparison is not EQ or NE");
8328 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8329 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
8330 (CC == ISD::SETNE && !Val);
8332 // We now need to make the intrinsic dead (it cannot be instruction
8334 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
8335 assert(LHS.getNode()->hasOneUse() &&
8336 "Counter decrement has more than one use");
8338 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
8339 N->getOperand(0), N->getOperand(4));
8345 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8346 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
8347 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
8348 assert(isDot && "Can't compare against a vector result!");
8350 // If this is a comparison against something other than 0/1, then we know
8351 // that the condition is never/always true.
8352 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8353 if (Val != 0 && Val != 1) {
8354 if (CC == ISD::SETEQ) // Cond never true, remove branch.
8355 return N->getOperand(0);
8356 // Always !=, turn it into an unconditional branch.
8357 return DAG.getNode(ISD::BR, dl, MVT::Other,
8358 N->getOperand(0), N->getOperand(4));
8361 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
8363 // Create the PPCISD altivec 'dot' comparison node.
8365 LHS.getOperand(2), // LHS of compare
8366 LHS.getOperand(3), // RHS of compare
8367 DAG.getConstant(CompareOpc, MVT::i32)
8369 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
8370 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8372 // Unpack the result based on how the target uses it.
8373 PPC::Predicate CompOpc;
8374 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
8375 default: // Can't happen, don't crash on invalid number though.
8376 case 0: // Branch on the value of the EQ bit of CR6.
8377 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
8379 case 1: // Branch on the inverted value of the EQ bit of CR6.
8380 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
8382 case 2: // Branch on the value of the LT bit of CR6.
8383 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
8385 case 3: // Branch on the inverted value of the LT bit of CR6.
8386 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
8390 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
8391 DAG.getConstant(CompOpc, MVT::i32),
8392 DAG.getRegister(PPC::CR6, MVT::i32),
8393 N->getOperand(4), CompNode.getValue(1));
8402 //===----------------------------------------------------------------------===//
8403 // Inline Assembly Support
8404 //===----------------------------------------------------------------------===//
8406 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8409 const SelectionDAG &DAG,
8410 unsigned Depth) const {
8411 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
8412 switch (Op.getOpcode()) {
8414 case PPCISD::LBRX: {
8415 // lhbrx is known to have the top bits cleared out.
8416 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
8417 KnownZero = 0xFFFF0000;
8420 case ISD::INTRINSIC_WO_CHAIN: {
8421 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
8423 case Intrinsic::ppc_altivec_vcmpbfp_p:
8424 case Intrinsic::ppc_altivec_vcmpeqfp_p:
8425 case Intrinsic::ppc_altivec_vcmpequb_p:
8426 case Intrinsic::ppc_altivec_vcmpequh_p:
8427 case Intrinsic::ppc_altivec_vcmpequw_p:
8428 case Intrinsic::ppc_altivec_vcmpgefp_p:
8429 case Intrinsic::ppc_altivec_vcmpgtfp_p:
8430 case Intrinsic::ppc_altivec_vcmpgtsb_p:
8431 case Intrinsic::ppc_altivec_vcmpgtsh_p:
8432 case Intrinsic::ppc_altivec_vcmpgtsw_p:
8433 case Intrinsic::ppc_altivec_vcmpgtub_p:
8434 case Intrinsic::ppc_altivec_vcmpgtuh_p:
8435 case Intrinsic::ppc_altivec_vcmpgtuw_p:
8436 KnownZero = ~1U; // All bits but the low one are known to be zero.
8444 /// getConstraintType - Given a constraint, return the type of
8445 /// constraint it is for this target.
8446 PPCTargetLowering::ConstraintType
8447 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
8448 if (Constraint.size() == 1) {
8449 switch (Constraint[0]) {
8456 return C_RegisterClass;
8458 // FIXME: While Z does indicate a memory constraint, it specifically
8459 // indicates an r+r address (used in conjunction with the 'y' modifier
8460 // in the replacement string). Currently, we're forcing the base
8461 // register to be r0 in the asm printer (which is interpreted as zero)
8462 // and forming the complete address in the second register. This is
8466 } else if (Constraint == "wc") { // individual CR bits.
8467 return C_RegisterClass;
8468 } else if (Constraint == "wa" || Constraint == "wd" ||
8469 Constraint == "wf" || Constraint == "ws") {
8470 return C_RegisterClass; // VSX registers.
8472 return TargetLowering::getConstraintType(Constraint);
8475 /// Examine constraint type and operand type and determine a weight value.
8476 /// This object must already have been set up with the operand type
8477 /// and the current alternative constraint selected.
8478 TargetLowering::ConstraintWeight
8479 PPCTargetLowering::getSingleConstraintMatchWeight(
8480 AsmOperandInfo &info, const char *constraint) const {
8481 ConstraintWeight weight = CW_Invalid;
8482 Value *CallOperandVal = info.CallOperandVal;
8483 // If we don't have a value, we can't do a match,
8484 // but allow it at the lowest weight.
8485 if (!CallOperandVal)
8487 Type *type = CallOperandVal->getType();
8489 // Look at the constraint type.
8490 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
8491 return CW_Register; // an individual CR bit.
8492 else if ((StringRef(constraint) == "wa" ||
8493 StringRef(constraint) == "wd" ||
8494 StringRef(constraint) == "wf") &&
8497 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
8500 switch (*constraint) {
8502 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8505 if (type->isIntegerTy())
8506 weight = CW_Register;
8509 if (type->isFloatTy())
8510 weight = CW_Register;
8513 if (type->isDoubleTy())
8514 weight = CW_Register;
8517 if (type->isVectorTy())
8518 weight = CW_Register;
8521 weight = CW_Register;
8530 std::pair<unsigned, const TargetRegisterClass*>
8531 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8533 if (Constraint.size() == 1) {
8534 // GCC RS6000 Constraint Letters
8535 switch (Constraint[0]) {
8537 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8538 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
8539 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
8541 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8542 return std::make_pair(0U, &PPC::G8RCRegClass);
8543 return std::make_pair(0U, &PPC::GPRCRegClass);
8545 if (VT == MVT::f32 || VT == MVT::i32)
8546 return std::make_pair(0U, &PPC::F4RCRegClass);
8547 if (VT == MVT::f64 || VT == MVT::i64)
8548 return std::make_pair(0U, &PPC::F8RCRegClass);
8551 return std::make_pair(0U, &PPC::VRRCRegClass);
8553 return std::make_pair(0U, &PPC::CRRCRegClass);
8555 } else if (Constraint == "wc") { // an individual CR bit.
8556 return std::make_pair(0U, &PPC::CRBITRCRegClass);
8557 } else if (Constraint == "wa" || Constraint == "wd" ||
8558 Constraint == "wf") {
8559 return std::make_pair(0U, &PPC::VSRCRegClass);
8560 } else if (Constraint == "ws") {
8561 return std::make_pair(0U, &PPC::VSFRCRegClass);
8564 std::pair<unsigned, const TargetRegisterClass*> R =
8565 TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8567 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
8568 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
8569 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
8571 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
8572 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
8573 if (R.first && VT == MVT::i64 && PPCSubTarget.isPPC64() &&
8574 PPC::GPRCRegClass.contains(R.first)) {
8575 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
8576 return std::make_pair(TRI->getMatchingSuperReg(R.first,
8577 PPC::sub_32, &PPC::G8RCRegClass),
8578 &PPC::G8RCRegClass);
8585 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8586 /// vector. If it is invalid, don't add anything to Ops.
8587 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8588 std::string &Constraint,
8589 std::vector<SDValue>&Ops,
8590 SelectionDAG &DAG) const {
8593 // Only support length 1 constraints.
8594 if (Constraint.length() > 1) return;
8596 char Letter = Constraint[0];
8607 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
8608 if (!CST) return; // Must be an immediate to match.
8609 unsigned Value = CST->getZExtValue();
8611 default: llvm_unreachable("Unknown constraint letter!");
8612 case 'I': // "I" is a signed 16-bit constant.
8613 if ((short)Value == (int)Value)
8614 Result = DAG.getTargetConstant(Value, Op.getValueType());
8616 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
8617 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
8618 if ((short)Value == 0)
8619 Result = DAG.getTargetConstant(Value, Op.getValueType());
8621 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
8622 if ((Value >> 16) == 0)
8623 Result = DAG.getTargetConstant(Value, Op.getValueType());
8625 case 'M': // "M" is a constant that is greater than 31.
8627 Result = DAG.getTargetConstant(Value, Op.getValueType());
8629 case 'N': // "N" is a positive constant that is an exact power of two.
8630 if ((int)Value > 0 && isPowerOf2_32(Value))
8631 Result = DAG.getTargetConstant(Value, Op.getValueType());
8633 case 'O': // "O" is the constant zero.
8635 Result = DAG.getTargetConstant(Value, Op.getValueType());
8637 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
8638 if ((short)-Value == (int)-Value)
8639 Result = DAG.getTargetConstant(Value, Op.getValueType());
8646 if (Result.getNode()) {
8647 Ops.push_back(Result);
8651 // Handle standard constraint letters.
8652 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
8655 // isLegalAddressingMode - Return true if the addressing mode represented
8656 // by AM is legal for this target, for a load/store of the specified type.
8657 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8659 // FIXME: PPC does not allow r+i addressing modes for vectors!
8661 // PPC allows a sign-extended 16-bit immediate field.
8662 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
8665 // No global is ever allowed as a base.
8669 // PPC only support r+r,
8671 case 0: // "r+i" or just "i", depending on HasBaseReg.
8674 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
8676 // Otherwise we have r+r or r+i.
8679 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
8681 // Allow 2*r as r+r.
8684 // No other scales are supported.
8691 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
8692 SelectionDAG &DAG) const {
8693 MachineFunction &MF = DAG.getMachineFunction();
8694 MachineFrameInfo *MFI = MF.getFrameInfo();
8695 MFI->setReturnAddressIsTaken(true);
8697 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
8701 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8703 // Make sure the function does not optimize away the store of the RA to
8705 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
8706 FuncInfo->setLRStoreRequired();
8707 bool isPPC64 = PPCSubTarget.isPPC64();
8708 bool isDarwinABI = PPCSubTarget.isDarwinABI();
8711 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8714 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
8715 isPPC64? MVT::i64 : MVT::i32);
8716 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8717 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8719 MachinePointerInfo(), false, false, false, 0);
8722 // Just load the return address off the stack.
8723 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
8724 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8725 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
8728 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
8729 SelectionDAG &DAG) const {
8731 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8733 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
8734 bool isPPC64 = PtrVT == MVT::i64;
8736 MachineFunction &MF = DAG.getMachineFunction();
8737 MachineFrameInfo *MFI = MF.getFrameInfo();
8738 MFI->setFrameAddressIsTaken(true);
8740 // Naked functions never have a frame pointer, and so we use r1. For all
8741 // other functions, this decision must be delayed until during PEI.
8743 if (MF.getFunction()->getAttributes().hasAttribute(
8744 AttributeSet::FunctionIndex, Attribute::Naked))
8745 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
8747 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
8749 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
8752 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
8753 FrameAddr, MachinePointerInfo(), false, false,
8758 // FIXME? Maybe this could be a TableGen attribute on some registers and
8759 // this table could be generated automatically from RegInfo.
8760 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
8762 bool isPPC64 = PPCSubTarget.isPPC64();
8763 bool isDarwinABI = PPCSubTarget.isDarwinABI();
8765 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
8766 (!isPPC64 && VT != MVT::i32))
8767 report_fatal_error("Invalid register global variable type");
8769 bool is64Bit = isPPC64 && VT == MVT::i64;
8770 unsigned Reg = StringSwitch<unsigned>(RegName)
8771 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
8772 .Case("r2", isDarwinABI ? 0 : (is64Bit ? PPC::X2 : PPC::R2))
8773 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
8774 (is64Bit ? PPC::X13 : PPC::R13))
8779 report_fatal_error("Invalid register name global variable");
8783 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
8784 // The PowerPC target isn't yet aware of offsets.
8788 /// getOptimalMemOpType - Returns the target specific optimal type for load
8789 /// and store operations as a result of memset, memcpy, and memmove
8790 /// lowering. If DstAlign is zero that means it's safe to destination
8791 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
8792 /// means there isn't a need to check it against alignment requirement,
8793 /// probably because the source does not need to be loaded. If 'IsMemset' is
8794 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
8795 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
8796 /// source is constant so it does not need to be loaded.
8797 /// It returns EVT::Other if the type should be determined using generic
8798 /// target-independent logic.
8799 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
8800 unsigned DstAlign, unsigned SrcAlign,
8801 bool IsMemset, bool ZeroMemset,
8803 MachineFunction &MF) const {
8804 if (this->PPCSubTarget.isPPC64()) {
8811 /// \brief Returns true if it is beneficial to convert a load of a constant
8812 /// to just the constant itself.
8813 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
8815 assert(Ty->isIntegerTy());
8817 unsigned BitSize = Ty->getPrimitiveSizeInBits();
8818 if (BitSize == 0 || BitSize > 64)
8823 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8824 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8826 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8827 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8828 return NumBits1 == 64 && NumBits2 == 32;
8831 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8832 if (!VT1.isInteger() || !VT2.isInteger())
8834 unsigned NumBits1 = VT1.getSizeInBits();
8835 unsigned NumBits2 = VT2.getSizeInBits();
8836 return NumBits1 == 64 && NumBits2 == 32;
8839 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
8840 return isInt<16>(Imm) || isUInt<16>(Imm);
8843 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
8844 return isInt<16>(Imm) || isUInt<16>(Imm);
8847 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
8850 if (DisablePPCUnaligned)
8853 // PowerPC supports unaligned memory access for simple non-vector types.
8854 // Although accessing unaligned addresses is not as efficient as accessing
8855 // aligned addresses, it is generally more efficient than manual expansion,
8856 // and generally only traps for software emulation when crossing page
8862 if (VT.getSimpleVT().isVector()) {
8863 if (PPCSubTarget.hasVSX()) {
8864 if (VT != MVT::v2f64 && VT != MVT::v2i64)
8871 if (VT == MVT::ppcf128)
8880 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8881 VT = VT.getScalarType();
8886 switch (VT.getSimpleVT().SimpleTy) {
8898 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
8899 EVT VT , unsigned DefinedValues) const {
8900 if (VT == MVT::v2i64)
8903 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
8906 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
8907 if (DisableILPPref || PPCSubTarget.enableMachineScheduler())
8908 return TargetLowering::getSchedulingPreference(N);
8913 // Create a fast isel object.
8915 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
8916 const TargetLibraryInfo *LibInfo) const {
8917 return PPC::createFastISel(FuncInfo, LibInfo);