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 "MCTargetDesc/PPCPredicates.h"
16 #include "PPCCallingConv.h"
17 #include "PPCCCState.h"
18 #include "PPCFrameLowering.h"
19 #include "PPCInstrInfo.h"
20 #include "PPCISelLowering.h"
21 #include "PPCMachineFunctionInfo.h"
22 #include "PPCPerfectShuffle.h"
23 #include "PPCRegisterInfo.h"
24 #include "PPCSubtarget.h"
25 #include "PPCTargetMachine.h"
26 #include "llvm/ADT/APFloat.h"
27 #include "llvm/ADT/APInt.h"
28 #include "llvm/ADT/ArrayRef.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/None.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/CodeGen/CallingConvLower.h"
39 #include "llvm/CodeGen/ISDOpcodes.h"
40 #include "llvm/CodeGen/MachineBasicBlock.h"
41 #include "llvm/CodeGen/MachineFrameInfo.h"
42 #include "llvm/CodeGen/MachineFunction.h"
43 #include "llvm/CodeGen/MachineInstr.h"
44 #include "llvm/CodeGen/MachineInstrBuilder.h"
45 #include "llvm/CodeGen/MachineJumpTableInfo.h"
46 #include "llvm/CodeGen/MachineLoopInfo.h"
47 #include "llvm/CodeGen/MachineMemOperand.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/MachineValueType.h"
51 #include "llvm/CodeGen/RuntimeLibcalls.h"
52 #include "llvm/CodeGen/SelectionDAG.h"
53 #include "llvm/CodeGen/SelectionDAGNodes.h"
54 #include "llvm/CodeGen/ValueTypes.h"
55 #include "llvm/IR/CallingConv.h"
56 #include "llvm/IR/CallSite.h"
57 #include "llvm/IR/Constant.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugLoc.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/Function.h"
63 #include "llvm/IR/GlobalValue.h"
64 #include "llvm/IR/Instructions.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/Module.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/Value.h"
71 #include "llvm/MC/MCExpr.h"
72 #include "llvm/MC/MCRegisterInfo.h"
73 #include "llvm/Support/AtomicOrdering.h"
74 #include "llvm/Support/BranchProbability.h"
75 #include "llvm/Support/Casting.h"
76 #include "llvm/Support/CodeGen.h"
77 #include "llvm/Support/CommandLine.h"
78 #include "llvm/Support/Compiler.h"
79 #include "llvm/Support/Debug.h"
80 #include "llvm/Support/ErrorHandling.h"
81 #include "llvm/Support/Format.h"
82 #include "llvm/Support/MathExtras.h"
83 #include "llvm/Support/raw_ostream.h"
84 #include "llvm/Target/TargetInstrInfo.h"
85 #include "llvm/Target/TargetLowering.h"
86 #include "llvm/Target/TargetMachine.h"
87 #include "llvm/Target/TargetOptions.h"
88 #include "llvm/Target/TargetRegisterInfo.h"
99 #define DEBUG_TYPE "ppc-lowering"
101 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
102 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
104 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
105 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
107 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
108 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
110 static cl::opt<bool> DisableSCO("disable-ppc-sco",
111 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
113 STATISTIC(NumTailCalls, "Number of tail calls");
114 STATISTIC(NumSiblingCalls, "Number of sibling calls");
116 // FIXME: Remove this once the bug has been fixed!
117 extern cl::opt<bool> ANDIGlueBug;
119 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
120 const PPCSubtarget &STI)
121 : TargetLowering(TM), Subtarget(STI) {
122 // Use _setjmp/_longjmp instead of setjmp/longjmp.
123 setUseUnderscoreSetJmp(true);
124 setUseUnderscoreLongJmp(true);
126 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
127 // arguments are at least 4/8 bytes aligned.
128 bool isPPC64 = Subtarget.isPPC64();
129 setMinStackArgumentAlignment(isPPC64 ? 8:4);
131 // Set up the register classes.
132 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
133 if (!useSoftFloat()) {
134 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
135 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
138 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
139 for (MVT VT : MVT::integer_valuetypes()) {
140 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
141 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
144 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
146 // PowerPC has pre-inc load and store's.
147 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
148 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
149 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
150 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
151 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
152 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
153 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
154 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
155 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
156 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
157 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
158 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
159 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
160 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
162 if (Subtarget.useCRBits()) {
163 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
165 if (isPPC64 || Subtarget.hasFPCVT()) {
166 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
167 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
168 isPPC64 ? MVT::i64 : MVT::i32);
169 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
170 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
171 isPPC64 ? MVT::i64 : MVT::i32);
173 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
174 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
177 // PowerPC does not support direct load / store of condition registers
178 setOperationAction(ISD::LOAD, MVT::i1, Custom);
179 setOperationAction(ISD::STORE, MVT::i1, Custom);
181 // FIXME: Remove this once the ANDI glue bug is fixed:
183 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
185 for (MVT VT : MVT::integer_valuetypes()) {
186 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
187 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
188 setTruncStoreAction(VT, MVT::i1, Expand);
191 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
194 // This is used in the ppcf128->int sequence. Note it has different semantics
195 // from FP_ROUND: that rounds to nearest, this rounds to zero.
196 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
198 // We do not currently implement these libm ops for PowerPC.
199 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
200 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
201 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
202 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
203 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
204 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
206 // PowerPC has no SREM/UREM instructions
207 setOperationAction(ISD::SREM, MVT::i32, Expand);
208 setOperationAction(ISD::UREM, MVT::i32, Expand);
209 setOperationAction(ISD::SREM, MVT::i64, Expand);
210 setOperationAction(ISD::UREM, MVT::i64, Expand);
212 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
213 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
214 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
215 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
216 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
217 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
218 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
219 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
220 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
222 // We don't support sin/cos/sqrt/fmod/pow
223 setOperationAction(ISD::FSIN , MVT::f64, Expand);
224 setOperationAction(ISD::FCOS , MVT::f64, Expand);
225 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
226 setOperationAction(ISD::FREM , MVT::f64, Expand);
227 setOperationAction(ISD::FPOW , MVT::f64, Expand);
228 setOperationAction(ISD::FMA , MVT::f64, Legal);
229 setOperationAction(ISD::FSIN , MVT::f32, Expand);
230 setOperationAction(ISD::FCOS , MVT::f32, Expand);
231 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
232 setOperationAction(ISD::FREM , MVT::f32, Expand);
233 setOperationAction(ISD::FPOW , MVT::f32, Expand);
234 setOperationAction(ISD::FMA , MVT::f32, Legal);
236 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
238 // If we're enabling GP optimizations, use hardware square root
239 if (!Subtarget.hasFSQRT() &&
240 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
242 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
244 if (!Subtarget.hasFSQRT() &&
245 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
246 Subtarget.hasFRES()))
247 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
249 if (Subtarget.hasFCPSGN()) {
250 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
251 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
253 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
254 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
257 if (Subtarget.hasFPRND()) {
258 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
259 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
260 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
261 setOperationAction(ISD::FROUND, MVT::f64, Legal);
263 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
264 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
265 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
266 setOperationAction(ISD::FROUND, MVT::f32, Legal);
269 // PowerPC does not have BSWAP
270 // CTPOP or CTTZ were introduced in P8/P9 respectivelly
271 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
272 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
273 if (Subtarget.isISA3_0()) {
274 setOperationAction(ISD::CTTZ , MVT::i32 , Legal);
275 setOperationAction(ISD::CTTZ , MVT::i64 , Legal);
277 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
278 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
281 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
282 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
283 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
285 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
286 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
289 // PowerPC does not have ROTR
290 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
291 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
293 if (!Subtarget.useCRBits()) {
294 // PowerPC does not have Select
295 setOperationAction(ISD::SELECT, MVT::i32, Expand);
296 setOperationAction(ISD::SELECT, MVT::i64, Expand);
297 setOperationAction(ISD::SELECT, MVT::f32, Expand);
298 setOperationAction(ISD::SELECT, MVT::f64, Expand);
301 // PowerPC wants to turn select_cc of FP into fsel when possible.
302 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
303 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
305 // PowerPC wants to optimize integer setcc a bit
306 if (!Subtarget.useCRBits())
307 setOperationAction(ISD::SETCC, MVT::i32, Custom);
309 // PowerPC does not have BRCOND which requires SetCC
310 if (!Subtarget.useCRBits())
311 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
313 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
315 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
316 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
318 // PowerPC does not have [U|S]INT_TO_FP
319 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
320 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
322 if (Subtarget.hasDirectMove() && isPPC64) {
323 setOperationAction(ISD::BITCAST, MVT::f32, Legal);
324 setOperationAction(ISD::BITCAST, MVT::i32, Legal);
325 setOperationAction(ISD::BITCAST, MVT::i64, Legal);
326 setOperationAction(ISD::BITCAST, MVT::f64, Legal);
328 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
329 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
330 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
331 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
334 // We cannot sextinreg(i1). Expand to shifts.
335 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
337 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
338 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
339 // support continuation, user-level threading, and etc.. As a result, no
340 // other SjLj exception interfaces are implemented and please don't build
341 // your own exception handling based on them.
342 // LLVM/Clang supports zero-cost DWARF exception handling.
343 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
344 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
346 // We want to legalize GlobalAddress and ConstantPool nodes into the
347 // appropriate instructions to materialize the address.
348 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
349 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
350 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
351 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
352 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
353 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
354 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
355 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
356 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
357 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
360 setOperationAction(ISD::TRAP, MVT::Other, Legal);
362 // TRAMPOLINE is custom lowered.
363 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
364 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
366 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
367 setOperationAction(ISD::VASTART , MVT::Other, Custom);
369 if (Subtarget.isSVR4ABI()) {
371 // VAARG always uses double-word chunks, so promote anything smaller.
372 setOperationAction(ISD::VAARG, MVT::i1, Promote);
373 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
374 setOperationAction(ISD::VAARG, MVT::i8, Promote);
375 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
376 setOperationAction(ISD::VAARG, MVT::i16, Promote);
377 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
378 setOperationAction(ISD::VAARG, MVT::i32, Promote);
379 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
380 setOperationAction(ISD::VAARG, MVT::Other, Expand);
382 // VAARG is custom lowered with the 32-bit SVR4 ABI.
383 setOperationAction(ISD::VAARG, MVT::Other, Custom);
384 setOperationAction(ISD::VAARG, MVT::i64, Custom);
387 setOperationAction(ISD::VAARG, MVT::Other, Expand);
389 if (Subtarget.isSVR4ABI() && !isPPC64)
390 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
391 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
393 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
395 // Use the default implementation.
396 setOperationAction(ISD::VAEND , MVT::Other, Expand);
397 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
398 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
399 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
400 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
401 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
402 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
403 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
404 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
406 // We want to custom lower some of our intrinsics.
407 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
409 // To handle counter-based loop conditions.
410 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
412 // Comparisons that require checking two conditions.
413 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
414 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
415 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
416 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
417 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
418 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
419 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
420 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
421 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
422 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
423 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
424 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
426 if (Subtarget.has64BitSupport()) {
427 // They also have instructions for converting between i64 and fp.
428 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
429 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
430 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
431 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
432 // This is just the low 32 bits of a (signed) fp->i64 conversion.
433 // We cannot do this with Promote because i64 is not a legal type.
434 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
436 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
437 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
439 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
440 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
443 // With the instructions enabled under FPCVT, we can do everything.
444 if (Subtarget.hasFPCVT()) {
445 if (Subtarget.has64BitSupport()) {
446 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
447 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
448 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
449 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
452 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
453 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
454 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
455 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
458 if (Subtarget.use64BitRegs()) {
459 // 64-bit PowerPC implementations can support i64 types directly
460 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
461 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
462 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
463 // 64-bit PowerPC wants to expand i128 shifts itself.
464 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
465 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
466 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
468 // 32-bit PowerPC wants to expand i64 shifts itself.
469 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
470 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
471 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
474 if (Subtarget.hasAltivec()) {
475 // First set operation action for all vector types to expand. Then we
476 // will selectively turn on ones that can be effectively codegen'd.
477 for (MVT VT : MVT::vector_valuetypes()) {
478 // add/sub are legal for all supported vector VT's.
479 setOperationAction(ISD::ADD, VT, Legal);
480 setOperationAction(ISD::SUB, VT, Legal);
482 // Vector instructions introduced in P8
483 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
484 setOperationAction(ISD::CTPOP, VT, Legal);
485 setOperationAction(ISD::CTLZ, VT, Legal);
488 setOperationAction(ISD::CTPOP, VT, Expand);
489 setOperationAction(ISD::CTLZ, VT, Expand);
492 // Vector instructions introduced in P9
493 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
494 setOperationAction(ISD::CTTZ, VT, Legal);
496 setOperationAction(ISD::CTTZ, VT, Expand);
498 // We promote all shuffles to v16i8.
499 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
500 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
502 // We promote all non-typed operations to v4i32.
503 setOperationAction(ISD::AND , VT, Promote);
504 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
505 setOperationAction(ISD::OR , VT, Promote);
506 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
507 setOperationAction(ISD::XOR , VT, Promote);
508 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
509 setOperationAction(ISD::LOAD , VT, Promote);
510 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
511 setOperationAction(ISD::SELECT, VT, Promote);
512 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
513 setOperationAction(ISD::SELECT_CC, VT, Promote);
514 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
515 setOperationAction(ISD::STORE, VT, Promote);
516 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
518 // No other operations are legal.
519 setOperationAction(ISD::MUL , VT, Expand);
520 setOperationAction(ISD::SDIV, VT, Expand);
521 setOperationAction(ISD::SREM, VT, Expand);
522 setOperationAction(ISD::UDIV, VT, Expand);
523 setOperationAction(ISD::UREM, VT, Expand);
524 setOperationAction(ISD::FDIV, VT, Expand);
525 setOperationAction(ISD::FREM, VT, Expand);
526 setOperationAction(ISD::FNEG, VT, Expand);
527 setOperationAction(ISD::FSQRT, VT, Expand);
528 setOperationAction(ISD::FLOG, VT, Expand);
529 setOperationAction(ISD::FLOG10, VT, Expand);
530 setOperationAction(ISD::FLOG2, VT, Expand);
531 setOperationAction(ISD::FEXP, VT, Expand);
532 setOperationAction(ISD::FEXP2, VT, Expand);
533 setOperationAction(ISD::FSIN, VT, Expand);
534 setOperationAction(ISD::FCOS, VT, Expand);
535 setOperationAction(ISD::FABS, VT, Expand);
536 setOperationAction(ISD::FPOWI, VT, Expand);
537 setOperationAction(ISD::FFLOOR, VT, Expand);
538 setOperationAction(ISD::FCEIL, VT, Expand);
539 setOperationAction(ISD::FTRUNC, VT, Expand);
540 setOperationAction(ISD::FRINT, VT, Expand);
541 setOperationAction(ISD::FNEARBYINT, VT, Expand);
542 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
543 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
544 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
545 setOperationAction(ISD::MULHU, VT, Expand);
546 setOperationAction(ISD::MULHS, VT, Expand);
547 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
548 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
549 setOperationAction(ISD::UDIVREM, VT, Expand);
550 setOperationAction(ISD::SDIVREM, VT, Expand);
551 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
552 setOperationAction(ISD::FPOW, VT, Expand);
553 setOperationAction(ISD::BSWAP, VT, Expand);
554 setOperationAction(ISD::VSELECT, VT, Expand);
555 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
556 setOperationAction(ISD::ROTL, VT, Expand);
557 setOperationAction(ISD::ROTR, VT, Expand);
559 for (MVT InnerVT : MVT::vector_valuetypes()) {
560 setTruncStoreAction(VT, InnerVT, Expand);
561 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
562 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
563 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
567 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
568 // with merges, splats, etc.
569 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
571 setOperationAction(ISD::AND , MVT::v4i32, Legal);
572 setOperationAction(ISD::OR , MVT::v4i32, Legal);
573 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
574 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
575 setOperationAction(ISD::SELECT, MVT::v4i32,
576 Subtarget.useCRBits() ? Legal : Expand);
577 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
578 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
579 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
580 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
581 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
582 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
583 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
584 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
585 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
587 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
588 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
589 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
590 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
592 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
593 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
595 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
596 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
597 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
600 if (Subtarget.hasP8Altivec())
601 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
603 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
605 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
606 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
608 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
609 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
611 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
612 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
613 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
614 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
616 // Altivec does not contain unordered floating-point compare instructions
617 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
618 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
619 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
620 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
622 if (Subtarget.hasVSX()) {
623 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
624 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
625 if (Subtarget.hasP8Vector()) {
626 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
627 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
629 if (Subtarget.hasDirectMove() && isPPC64) {
630 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
631 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
632 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
633 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
634 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
635 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
636 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
637 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
639 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
641 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
642 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
643 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
644 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
645 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
647 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
649 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
650 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
652 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
653 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
655 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
656 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
657 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
658 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
659 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
661 // Share the Altivec comparison restrictions.
662 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
663 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
664 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
665 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
667 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
668 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
670 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
672 if (Subtarget.hasP8Vector())
673 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
675 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
677 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
678 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
679 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
681 if (Subtarget.hasP8Altivec()) {
682 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
683 setOperationAction(ISD::SRA, MVT::v2i64, Legal);
684 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
686 setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
689 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
690 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
691 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
693 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
695 // VSX v2i64 only supports non-arithmetic operations.
696 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
697 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
700 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
701 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
702 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
703 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
705 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
707 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
708 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
709 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
710 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
712 // Vector operation legalization checks the result type of
713 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
714 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
715 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
716 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
717 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
719 setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
720 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
721 setOperationAction(ISD::FABS, MVT::v4f32, Legal);
722 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
724 if (Subtarget.hasDirectMove())
725 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
726 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
728 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
731 if (Subtarget.hasP8Altivec()) {
732 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
733 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
736 if (Subtarget.hasP9Vector()) {
737 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
738 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
742 if (Subtarget.hasQPX()) {
743 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
744 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
745 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
746 setOperationAction(ISD::FREM, MVT::v4f64, Expand);
748 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
749 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
751 setOperationAction(ISD::LOAD , MVT::v4f64, Custom);
752 setOperationAction(ISD::STORE , MVT::v4f64, Custom);
754 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
755 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
757 if (!Subtarget.useCRBits())
758 setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
759 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
761 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
762 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
763 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
764 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
765 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
766 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
767 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
769 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
770 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
772 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
773 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
774 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
776 setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
777 setOperationAction(ISD::FABS , MVT::v4f64, Legal);
778 setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
779 setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
780 setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
781 setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
782 setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
783 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
784 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
785 setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
786 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
788 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
789 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
791 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
792 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
794 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
796 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
797 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
798 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
799 setOperationAction(ISD::FREM, MVT::v4f32, Expand);
801 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
802 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
804 setOperationAction(ISD::LOAD , MVT::v4f32, Custom);
805 setOperationAction(ISD::STORE , MVT::v4f32, Custom);
807 if (!Subtarget.useCRBits())
808 setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
809 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
811 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
812 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
813 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
814 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
815 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
816 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
817 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
819 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
820 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
822 setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
823 setOperationAction(ISD::FABS , MVT::v4f32, Legal);
824 setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
825 setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
826 setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
827 setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
828 setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
829 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
830 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
831 setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
832 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
834 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
835 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
837 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
838 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
840 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
842 setOperationAction(ISD::AND , MVT::v4i1, Legal);
843 setOperationAction(ISD::OR , MVT::v4i1, Legal);
844 setOperationAction(ISD::XOR , MVT::v4i1, Legal);
846 if (!Subtarget.useCRBits())
847 setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
848 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
850 setOperationAction(ISD::LOAD , MVT::v4i1, Custom);
851 setOperationAction(ISD::STORE , MVT::v4i1, Custom);
853 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
854 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
855 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
856 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
857 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
858 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
859 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
861 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
862 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
864 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
866 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
867 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
868 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
869 setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
871 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
872 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
873 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
874 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
876 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
877 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
879 // These need to set FE_INEXACT, and so cannot be vectorized here.
880 setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
881 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
883 if (TM.Options.UnsafeFPMath) {
884 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
885 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
887 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
888 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
890 setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
891 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
893 setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
894 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
898 if (Subtarget.has64BitSupport())
899 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
901 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
904 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
905 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
908 setBooleanContents(ZeroOrOneBooleanContent);
910 if (Subtarget.hasAltivec()) {
911 // Altivec instructions set fields to all zeros or all ones.
912 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
916 // These libcalls are not available in 32-bit.
917 setLibcallName(RTLIB::SHL_I128, nullptr);
918 setLibcallName(RTLIB::SRL_I128, nullptr);
919 setLibcallName(RTLIB::SRA_I128, nullptr);
922 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
924 // We have target-specific dag combine patterns for the following nodes:
925 setTargetDAGCombine(ISD::SINT_TO_FP);
926 setTargetDAGCombine(ISD::BUILD_VECTOR);
927 if (Subtarget.hasFPCVT())
928 setTargetDAGCombine(ISD::UINT_TO_FP);
929 setTargetDAGCombine(ISD::LOAD);
930 setTargetDAGCombine(ISD::STORE);
931 setTargetDAGCombine(ISD::BR_CC);
932 if (Subtarget.useCRBits())
933 setTargetDAGCombine(ISD::BRCOND);
934 setTargetDAGCombine(ISD::BSWAP);
935 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
936 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
937 setTargetDAGCombine(ISD::INTRINSIC_VOID);
939 setTargetDAGCombine(ISD::SIGN_EXTEND);
940 setTargetDAGCombine(ISD::ZERO_EXTEND);
941 setTargetDAGCombine(ISD::ANY_EXTEND);
943 if (Subtarget.useCRBits()) {
944 setTargetDAGCombine(ISD::TRUNCATE);
945 setTargetDAGCombine(ISD::SETCC);
946 setTargetDAGCombine(ISD::SELECT_CC);
949 // Use reciprocal estimates.
950 if (TM.Options.UnsafeFPMath) {
951 setTargetDAGCombine(ISD::FDIV);
952 setTargetDAGCombine(ISD::FSQRT);
955 // Darwin long double math library functions have $LDBL128 appended.
956 if (Subtarget.isDarwin()) {
957 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
958 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
959 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
960 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
961 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
962 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
963 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
964 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
965 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
966 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
969 // With 32 condition bits, we don't need to sink (and duplicate) compares
970 // aggressively in CodeGenPrep.
971 if (Subtarget.useCRBits()) {
972 setHasMultipleConditionRegisters();
973 setJumpIsExpensive();
976 setMinFunctionAlignment(2);
977 if (Subtarget.isDarwin())
978 setPrefFunctionAlignment(4);
980 switch (Subtarget.getDarwinDirective()) {
984 case PPC::DIR_E500mc:
994 setPrefFunctionAlignment(4);
995 setPrefLoopAlignment(4);
999 if (Subtarget.enableMachineScheduler())
1000 setSchedulingPreference(Sched::Source);
1002 setSchedulingPreference(Sched::Hybrid);
1004 computeRegisterProperties(STI.getRegisterInfo());
1006 // The Freescale cores do better with aggressive inlining of memcpy and
1007 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1008 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1009 Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1010 MaxStoresPerMemset = 32;
1011 MaxStoresPerMemsetOptSize = 16;
1012 MaxStoresPerMemcpy = 32;
1013 MaxStoresPerMemcpyOptSize = 8;
1014 MaxStoresPerMemmove = 32;
1015 MaxStoresPerMemmoveOptSize = 8;
1016 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1017 // The A2 also benefits from (very) aggressive inlining of memcpy and
1018 // friends. The overhead of a the function call, even when warm, can be
1019 // over one hundred cycles.
1020 MaxStoresPerMemset = 128;
1021 MaxStoresPerMemcpy = 128;
1022 MaxStoresPerMemmove = 128;
1026 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1027 /// the desired ByVal argument alignment.
1028 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1029 unsigned MaxMaxAlign) {
1030 if (MaxAlign == MaxMaxAlign)
1032 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1033 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1035 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1037 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1038 unsigned EltAlign = 0;
1039 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1040 if (EltAlign > MaxAlign)
1041 MaxAlign = EltAlign;
1042 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1043 for (auto *EltTy : STy->elements()) {
1044 unsigned EltAlign = 0;
1045 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1046 if (EltAlign > MaxAlign)
1047 MaxAlign = EltAlign;
1048 if (MaxAlign == MaxMaxAlign)
1054 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1055 /// function arguments in the caller parameter area.
1056 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1057 const DataLayout &DL) const {
1058 // Darwin passes everything on 4 byte boundary.
1059 if (Subtarget.isDarwin())
1062 // 16byte and wider vectors are passed on 16byte boundary.
1063 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1064 unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1065 if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1066 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1070 bool PPCTargetLowering::useSoftFloat() const {
1071 return Subtarget.useSoftFloat();
1074 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1075 switch ((PPCISD::NodeType)Opcode) {
1076 case PPCISD::FIRST_NUMBER: break;
1077 case PPCISD::FSEL: return "PPCISD::FSEL";
1078 case PPCISD::FCFID: return "PPCISD::FCFID";
1079 case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
1080 case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
1081 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
1082 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
1083 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
1084 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
1085 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
1086 case PPCISD::FRE: return "PPCISD::FRE";
1087 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
1088 case PPCISD::STFIWX: return "PPCISD::STFIWX";
1089 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
1090 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
1091 case PPCISD::VPERM: return "PPCISD::VPERM";
1092 case PPCISD::XXSPLT: return "PPCISD::XXSPLT";
1093 case PPCISD::XXINSERT: return "PPCISD::XXINSERT";
1094 case PPCISD::VECSHL: return "PPCISD::VECSHL";
1095 case PPCISD::CMPB: return "PPCISD::CMPB";
1096 case PPCISD::Hi: return "PPCISD::Hi";
1097 case PPCISD::Lo: return "PPCISD::Lo";
1098 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
1099 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
1100 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET";
1101 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
1102 case PPCISD::SRL: return "PPCISD::SRL";
1103 case PPCISD::SRA: return "PPCISD::SRA";
1104 case PPCISD::SHL: return "PPCISD::SHL";
1105 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE";
1106 case PPCISD::CALL: return "PPCISD::CALL";
1107 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
1108 case PPCISD::MTCTR: return "PPCISD::MTCTR";
1109 case PPCISD::BCTRL: return "PPCISD::BCTRL";
1110 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
1111 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
1112 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
1113 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
1114 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1115 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
1116 case PPCISD::MFVSR: return "PPCISD::MFVSR";
1117 case PPCISD::MTVSRA: return "PPCISD::MTVSRA";
1118 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ";
1119 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP";
1120 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP";
1121 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT";
1122 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT";
1123 case PPCISD::VCMP: return "PPCISD::VCMP";
1124 case PPCISD::VCMPo: return "PPCISD::VCMPo";
1125 case PPCISD::LBRX: return "PPCISD::LBRX";
1126 case PPCISD::STBRX: return "PPCISD::STBRX";
1127 case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
1128 case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
1129 case PPCISD::LXSIZX: return "PPCISD::LXSIZX";
1130 case PPCISD::STXSIX: return "PPCISD::STXSIX";
1131 case PPCISD::VEXTS: return "PPCISD::VEXTS";
1132 case PPCISD::LXVD2X: return "PPCISD::LXVD2X";
1133 case PPCISD::STXVD2X: return "PPCISD::STXVD2X";
1134 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
1135 case PPCISD::BDNZ: return "PPCISD::BDNZ";
1136 case PPCISD::BDZ: return "PPCISD::BDZ";
1137 case PPCISD::MFFS: return "PPCISD::MFFS";
1138 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
1139 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
1140 case PPCISD::CR6SET: return "PPCISD::CR6SET";
1141 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
1142 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
1143 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT";
1144 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1145 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
1146 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
1147 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
1148 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
1149 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
1150 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1151 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
1152 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
1153 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
1154 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1155 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1156 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
1157 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
1158 case PPCISD::SC: return "PPCISD::SC";
1159 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB";
1160 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE";
1161 case PPCISD::RFEBB: return "PPCISD::RFEBB";
1162 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD";
1163 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN";
1164 case PPCISD::QVFPERM: return "PPCISD::QVFPERM";
1165 case PPCISD::QVGPCI: return "PPCISD::QVGPCI";
1166 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI";
1167 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI";
1168 case PPCISD::QBFLT: return "PPCISD::QBFLT";
1169 case PPCISD::QVLFSb: return "PPCISD::QVLFSb";
1174 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1177 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1179 if (Subtarget.hasQPX())
1180 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1182 return VT.changeVectorElementTypeToInteger();
1185 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1186 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1190 //===----------------------------------------------------------------------===//
1191 // Node matching predicates, for use by the tblgen matching code.
1192 //===----------------------------------------------------------------------===//
1194 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1195 static bool isFloatingPointZero(SDValue Op) {
1196 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1197 return CFP->getValueAPF().isZero();
1198 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1199 // Maybe this has already been legalized into the constant pool?
1200 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1201 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1202 return CFP->getValueAPF().isZero();
1207 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1208 /// true if Op is undef or if it matches the specified value.
1209 static bool isConstantOrUndef(int Op, int Val) {
1210 return Op < 0 || Op == Val;
1213 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1214 /// VPKUHUM instruction.
1215 /// The ShuffleKind distinguishes between big-endian operations with
1216 /// two different inputs (0), either-endian operations with two identical
1217 /// inputs (1), and little-endian operations with two different inputs (2).
1218 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1219 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1220 SelectionDAG &DAG) {
1221 bool IsLE = DAG.getDataLayout().isLittleEndian();
1222 if (ShuffleKind == 0) {
1225 for (unsigned i = 0; i != 16; ++i)
1226 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1228 } else if (ShuffleKind == 2) {
1231 for (unsigned i = 0; i != 16; ++i)
1232 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1234 } else if (ShuffleKind == 1) {
1235 unsigned j = IsLE ? 0 : 1;
1236 for (unsigned i = 0; i != 8; ++i)
1237 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1238 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1244 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1245 /// VPKUWUM instruction.
1246 /// The ShuffleKind distinguishes between big-endian operations with
1247 /// two different inputs (0), either-endian operations with two identical
1248 /// inputs (1), and little-endian operations with two different inputs (2).
1249 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1250 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1251 SelectionDAG &DAG) {
1252 bool IsLE = DAG.getDataLayout().isLittleEndian();
1253 if (ShuffleKind == 0) {
1256 for (unsigned i = 0; i != 16; i += 2)
1257 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1258 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1260 } else if (ShuffleKind == 2) {
1263 for (unsigned i = 0; i != 16; i += 2)
1264 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1265 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1267 } else if (ShuffleKind == 1) {
1268 unsigned j = IsLE ? 0 : 2;
1269 for (unsigned i = 0; i != 8; i += 2)
1270 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1271 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1272 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1273 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1279 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1280 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1281 /// current subtarget.
1283 /// The ShuffleKind distinguishes between big-endian operations with
1284 /// two different inputs (0), either-endian operations with two identical
1285 /// inputs (1), and little-endian operations with two different inputs (2).
1286 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1287 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1288 SelectionDAG &DAG) {
1289 const PPCSubtarget& Subtarget =
1290 static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1291 if (!Subtarget.hasP8Vector())
1294 bool IsLE = DAG.getDataLayout().isLittleEndian();
1295 if (ShuffleKind == 0) {
1298 for (unsigned i = 0; i != 16; i += 4)
1299 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) ||
1300 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) ||
1301 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) ||
1302 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7))
1304 } else if (ShuffleKind == 2) {
1307 for (unsigned i = 0; i != 16; i += 4)
1308 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1309 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) ||
1310 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) ||
1311 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3))
1313 } else if (ShuffleKind == 1) {
1314 unsigned j = IsLE ? 0 : 4;
1315 for (unsigned i = 0; i != 8; i += 4)
1316 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1317 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1318 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) ||
1319 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) ||
1320 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1321 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) ||
1322 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1323 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1329 /// isVMerge - Common function, used to match vmrg* shuffles.
1331 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1332 unsigned LHSStart, unsigned RHSStart) {
1333 if (N->getValueType(0) != MVT::v16i8)
1335 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1336 "Unsupported merge size!");
1338 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
1339 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
1340 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1341 LHSStart+j+i*UnitSize) ||
1342 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1343 RHSStart+j+i*UnitSize))
1349 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1350 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1351 /// The ShuffleKind distinguishes between big-endian merges with two
1352 /// different inputs (0), either-endian merges with two identical inputs (1),
1353 /// and little-endian merges with two different inputs (2). For the latter,
1354 /// the input operands are swapped (see PPCInstrAltivec.td).
1355 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1356 unsigned ShuffleKind, SelectionDAG &DAG) {
1357 if (DAG.getDataLayout().isLittleEndian()) {
1358 if (ShuffleKind == 1) // unary
1359 return isVMerge(N, UnitSize, 0, 0);
1360 else if (ShuffleKind == 2) // swapped
1361 return isVMerge(N, UnitSize, 0, 16);
1365 if (ShuffleKind == 1) // unary
1366 return isVMerge(N, UnitSize, 8, 8);
1367 else if (ShuffleKind == 0) // normal
1368 return isVMerge(N, UnitSize, 8, 24);
1374 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1375 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1376 /// The ShuffleKind distinguishes between big-endian merges with two
1377 /// different inputs (0), either-endian merges with two identical inputs (1),
1378 /// and little-endian merges with two different inputs (2). For the latter,
1379 /// the input operands are swapped (see PPCInstrAltivec.td).
1380 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1381 unsigned ShuffleKind, SelectionDAG &DAG) {
1382 if (DAG.getDataLayout().isLittleEndian()) {
1383 if (ShuffleKind == 1) // unary
1384 return isVMerge(N, UnitSize, 8, 8);
1385 else if (ShuffleKind == 2) // swapped
1386 return isVMerge(N, UnitSize, 8, 24);
1390 if (ShuffleKind == 1) // unary
1391 return isVMerge(N, UnitSize, 0, 0);
1392 else if (ShuffleKind == 0) // normal
1393 return isVMerge(N, UnitSize, 0, 16);
1400 * \brief Common function used to match vmrgew and vmrgow shuffles
1402 * The indexOffset determines whether to look for even or odd words in
1403 * the shuffle mask. This is based on the of the endianness of the target
1406 * - Use offset of 0 to check for odd elements
1407 * - Use offset of 4 to check for even elements
1409 * - Use offset of 0 to check for even elements
1410 * - Use offset of 4 to check for odd elements
1411 * A detailed description of the vector element ordering for little endian and
1412 * big endian can be found at
1413 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1414 * Targeting your applications - what little endian and big endian IBM XL C/C++
1415 * compiler differences mean to you
1417 * The mask to the shuffle vector instruction specifies the indices of the
1418 * elements from the two input vectors to place in the result. The elements are
1419 * numbered in array-access order, starting with the first vector. These vectors
1420 * are always of type v16i8, thus each vector will contain 16 elements of size
1421 * 8. More info on the shuffle vector can be found in the
1422 * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1423 * Language Reference.
1425 * The RHSStartValue indicates whether the same input vectors are used (unary)
1426 * or two different input vectors are used, based on the following:
1427 * - If the instruction uses the same vector for both inputs, the range of the
1428 * indices will be 0 to 15. In this case, the RHSStart value passed should
1430 * - If the instruction has two different vectors then the range of the
1431 * indices will be 0 to 31. In this case, the RHSStart value passed should
1432 * be 16 (indices 0-15 specify elements in the first vector while indices 16
1433 * to 31 specify elements in the second vector).
1435 * \param[in] N The shuffle vector SD Node to analyze
1436 * \param[in] IndexOffset Specifies whether to look for even or odd elements
1437 * \param[in] RHSStartValue Specifies the starting index for the righthand input
1438 * vector to the shuffle_vector instruction
1439 * \return true iff this shuffle vector represents an even or odd word merge
1441 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1442 unsigned RHSStartValue) {
1443 if (N->getValueType(0) != MVT::v16i8)
1446 for (unsigned i = 0; i < 2; ++i)
1447 for (unsigned j = 0; j < 4; ++j)
1448 if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1449 i*RHSStartValue+j+IndexOffset) ||
1450 !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1451 i*RHSStartValue+j+IndexOffset+8))
1457 * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1458 * vmrgow instructions.
1460 * \param[in] N The shuffle vector SD Node to analyze
1461 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1462 * \param[in] ShuffleKind Identify the type of merge:
1463 * - 0 = big-endian merge with two different inputs;
1464 * - 1 = either-endian merge with two identical inputs;
1465 * - 2 = little-endian merge with two different inputs (inputs are swapped for
1466 * little-endian merges).
1467 * \param[in] DAG The current SelectionDAG
1468 * \return true iff this shuffle mask
1470 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1471 unsigned ShuffleKind, SelectionDAG &DAG) {
1472 if (DAG.getDataLayout().isLittleEndian()) {
1473 unsigned indexOffset = CheckEven ? 4 : 0;
1474 if (ShuffleKind == 1) // Unary
1475 return isVMerge(N, indexOffset, 0);
1476 else if (ShuffleKind == 2) // swapped
1477 return isVMerge(N, indexOffset, 16);
1482 unsigned indexOffset = CheckEven ? 0 : 4;
1483 if (ShuffleKind == 1) // Unary
1484 return isVMerge(N, indexOffset, 0);
1485 else if (ShuffleKind == 0) // Normal
1486 return isVMerge(N, indexOffset, 16);
1493 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1494 /// amount, otherwise return -1.
1495 /// The ShuffleKind distinguishes between big-endian operations with two
1496 /// different inputs (0), either-endian operations with two identical inputs
1497 /// (1), and little-endian operations with two different inputs (2). For the
1498 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1499 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1500 SelectionDAG &DAG) {
1501 if (N->getValueType(0) != MVT::v16i8)
1504 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1506 // Find the first non-undef value in the shuffle mask.
1508 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1511 if (i == 16) return -1; // all undef.
1513 // Otherwise, check to see if the rest of the elements are consecutively
1514 // numbered from this value.
1515 unsigned ShiftAmt = SVOp->getMaskElt(i);
1516 if (ShiftAmt < i) return -1;
1519 bool isLE = DAG.getDataLayout().isLittleEndian();
1521 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1522 // Check the rest of the elements to see if they are consecutive.
1523 for (++i; i != 16; ++i)
1524 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1526 } else if (ShuffleKind == 1) {
1527 // Check the rest of the elements to see if they are consecutive.
1528 for (++i; i != 16; ++i)
1529 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1535 ShiftAmt = 16 - ShiftAmt;
1540 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1541 /// specifies a splat of a single element that is suitable for input to
1542 /// VSPLTB/VSPLTH/VSPLTW.
1543 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1544 assert(N->getValueType(0) == MVT::v16i8 &&
1545 (EltSize == 1 || EltSize == 2 || EltSize == 4));
1547 // The consecutive indices need to specify an element, not part of two
1548 // different elements. So abandon ship early if this isn't the case.
1549 if (N->getMaskElt(0) % EltSize != 0)
1552 // This is a splat operation if each element of the permute is the same, and
1553 // if the value doesn't reference the second vector.
1554 unsigned ElementBase = N->getMaskElt(0);
1556 // FIXME: Handle UNDEF elements too!
1557 if (ElementBase >= 16)
1560 // Check that the indices are consecutive, in the case of a multi-byte element
1561 // splatted with a v16i8 mask.
1562 for (unsigned i = 1; i != EltSize; ++i)
1563 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1566 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1567 if (N->getMaskElt(i) < 0) continue;
1568 for (unsigned j = 0; j != EltSize; ++j)
1569 if (N->getMaskElt(i+j) != N->getMaskElt(j))
1575 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1576 unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1577 // Check that the mask is shuffling words
1578 for (unsigned i = 0; i < 4; ++i) {
1579 unsigned B0 = N->getMaskElt(i*4);
1580 unsigned B1 = N->getMaskElt(i*4+1);
1581 unsigned B2 = N->getMaskElt(i*4+2);
1582 unsigned B3 = N->getMaskElt(i*4+3);
1585 if (B1 != B0+1 || B2 != B1+1 || B3 != B2+1)
1589 // Now we look at mask elements 0,4,8,12
1590 unsigned M0 = N->getMaskElt(0) / 4;
1591 unsigned M1 = N->getMaskElt(4) / 4;
1592 unsigned M2 = N->getMaskElt(8) / 4;
1593 unsigned M3 = N->getMaskElt(12) / 4;
1594 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1595 unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1597 // Below, let H and L be arbitrary elements of the shuffle mask
1598 // where H is in the range [4,7] and L is in the range [0,3].
1599 // H, 1, 2, 3 or L, 5, 6, 7
1600 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1601 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1602 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1603 InsertAtByte = IsLE ? 12 : 0;
1607 // 0, H, 2, 3 or 4, L, 6, 7
1608 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1609 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1610 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1611 InsertAtByte = IsLE ? 8 : 4;
1615 // 0, 1, H, 3 or 4, 5, L, 7
1616 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1617 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1618 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1619 InsertAtByte = IsLE ? 4 : 8;
1623 // 0, 1, 2, H or 4, 5, 6, L
1624 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1625 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1626 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1627 InsertAtByte = IsLE ? 0 : 12;
1632 // If both vector operands for the shuffle are the same vector, the mask will
1633 // contain only elements from the first one and the second one will be undef.
1634 if (N->getOperand(1).isUndef()) {
1637 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1638 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1639 InsertAtByte = IsLE ? 12 : 0;
1642 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1643 InsertAtByte = IsLE ? 8 : 4;
1646 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1647 InsertAtByte = IsLE ? 4 : 8;
1650 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1651 InsertAtByte = IsLE ? 0 : 12;
1659 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1660 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1661 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1662 SelectionDAG &DAG) {
1663 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1664 assert(isSplatShuffleMask(SVOp, EltSize));
1665 if (DAG.getDataLayout().isLittleEndian())
1666 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1668 return SVOp->getMaskElt(0) / EltSize;
1671 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1672 /// by using a vspltis[bhw] instruction of the specified element size, return
1673 /// the constant being splatted. The ByteSize field indicates the number of
1674 /// bytes of each element [124] -> [bhw].
1675 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1676 SDValue OpVal(nullptr, 0);
1678 // If ByteSize of the splat is bigger than the element size of the
1679 // build_vector, then we have a case where we are checking for a splat where
1680 // multiple elements of the buildvector are folded together into a single
1681 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1682 unsigned EltSize = 16/N->getNumOperands();
1683 if (EltSize < ByteSize) {
1684 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1685 SDValue UniquedVals[4];
1686 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1688 // See if all of the elements in the buildvector agree across.
1689 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1690 if (N->getOperand(i).isUndef()) continue;
1691 // If the element isn't a constant, bail fully out.
1692 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1694 if (!UniquedVals[i&(Multiple-1)].getNode())
1695 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1696 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1697 return SDValue(); // no match.
1700 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1701 // either constant or undef values that are identical for each chunk. See
1702 // if these chunks can form into a larger vspltis*.
1704 // Check to see if all of the leading entries are either 0 or -1. If
1705 // neither, then this won't fit into the immediate field.
1706 bool LeadingZero = true;
1707 bool LeadingOnes = true;
1708 for (unsigned i = 0; i != Multiple-1; ++i) {
1709 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1711 LeadingZero &= isNullConstant(UniquedVals[i]);
1712 LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1714 // Finally, check the least significant entry.
1716 if (!UniquedVals[Multiple-1].getNode())
1717 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
1718 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1719 if (Val < 16) // 0,0,0,4 -> vspltisw(4)
1720 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1723 if (!UniquedVals[Multiple-1].getNode())
1724 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1725 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1726 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1727 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1733 // Check to see if this buildvec has a single non-undef value in its elements.
1734 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1735 if (N->getOperand(i).isUndef()) continue;
1736 if (!OpVal.getNode())
1737 OpVal = N->getOperand(i);
1738 else if (OpVal != N->getOperand(i))
1742 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1744 unsigned ValSizeInBytes = EltSize;
1746 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1747 Value = CN->getZExtValue();
1748 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1749 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1750 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1753 // If the splat value is larger than the element value, then we can never do
1754 // this splat. The only case that we could fit the replicated bits into our
1755 // immediate field for would be zero, and we prefer to use vxor for it.
1756 if (ValSizeInBytes < ByteSize) return SDValue();
1758 // If the element value is larger than the splat value, check if it consists
1759 // of a repeated bit pattern of size ByteSize.
1760 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1763 // Properly sign extend the value.
1764 int MaskVal = SignExtend32(Value, ByteSize * 8);
1766 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1767 if (MaskVal == 0) return SDValue();
1769 // Finally, if this value fits in a 5 bit sext field, return it
1770 if (SignExtend32<5>(MaskVal) == MaskVal)
1771 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1775 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1776 /// amount, otherwise return -1.
1777 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1778 EVT VT = N->getValueType(0);
1779 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1782 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1784 // Find the first non-undef value in the shuffle mask.
1786 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1789 if (i == 4) return -1; // all undef.
1791 // Otherwise, check to see if the rest of the elements are consecutively
1792 // numbered from this value.
1793 unsigned ShiftAmt = SVOp->getMaskElt(i);
1794 if (ShiftAmt < i) return -1;
1797 // Check the rest of the elements to see if they are consecutive.
1798 for (++i; i != 4; ++i)
1799 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1805 //===----------------------------------------------------------------------===//
1806 // Addressing Mode Selection
1807 //===----------------------------------------------------------------------===//
1809 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1810 /// or 64-bit immediate, and if the value can be accurately represented as a
1811 /// sign extension from a 16-bit value. If so, this returns true and the
1813 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1814 if (!isa<ConstantSDNode>(N))
1817 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1818 if (N->getValueType(0) == MVT::i32)
1819 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1821 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1823 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1824 return isIntS16Immediate(Op.getNode(), Imm);
1827 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1828 /// can be represented as an indexed [r+r] operation. Returns false if it
1829 /// can be more efficiently represented with [r+imm].
1830 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1832 SelectionDAG &DAG) const {
1834 if (N.getOpcode() == ISD::ADD) {
1835 if (isIntS16Immediate(N.getOperand(1), imm))
1836 return false; // r+i
1837 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1838 return false; // r+i
1840 Base = N.getOperand(0);
1841 Index = N.getOperand(1);
1843 } else if (N.getOpcode() == ISD::OR) {
1844 if (isIntS16Immediate(N.getOperand(1), imm))
1845 return false; // r+i can fold it if we can.
1847 // If this is an or of disjoint bitfields, we can codegen this as an add
1848 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1850 APInt LHSKnownZero, LHSKnownOne;
1851 APInt RHSKnownZero, RHSKnownOne;
1852 DAG.computeKnownBits(N.getOperand(0),
1853 LHSKnownZero, LHSKnownOne);
1855 if (LHSKnownZero.getBoolValue()) {
1856 DAG.computeKnownBits(N.getOperand(1),
1857 RHSKnownZero, RHSKnownOne);
1858 // If all of the bits are known zero on the LHS or RHS, the add won't
1860 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1861 Base = N.getOperand(0);
1862 Index = N.getOperand(1);
1871 // If we happen to be doing an i64 load or store into a stack slot that has
1872 // less than a 4-byte alignment, then the frame-index elimination may need to
1873 // use an indexed load or store instruction (because the offset may not be a
1874 // multiple of 4). The extra register needed to hold the offset comes from the
1875 // register scavenger, and it is possible that the scavenger will need to use
1876 // an emergency spill slot. As a result, we need to make sure that a spill slot
1877 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1879 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1880 // FIXME: This does not handle the LWA case.
1884 // NOTE: We'll exclude negative FIs here, which come from argument
1885 // lowering, because there are no known test cases triggering this problem
1886 // using packed structures (or similar). We can remove this exclusion if
1887 // we find such a test case. The reason why this is so test-case driven is
1888 // because this entire 'fixup' is only to prevent crashes (from the
1889 // register scavenger) on not-really-valid inputs. For example, if we have:
1891 // %b = bitcast i1* %a to i64*
1892 // store i64* a, i64 b
1893 // then the store should really be marked as 'align 1', but is not. If it
1894 // were marked as 'align 1' then the indexed form would have been
1895 // instruction-selected initially, and the problem this 'fixup' is preventing
1896 // won't happen regardless.
1900 MachineFunction &MF = DAG.getMachineFunction();
1901 MachineFrameInfo &MFI = MF.getFrameInfo();
1903 unsigned Align = MFI.getObjectAlignment(FrameIdx);
1907 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1908 FuncInfo->setHasNonRISpills();
1911 /// Returns true if the address N can be represented by a base register plus
1912 /// a signed 16-bit displacement [r+imm], and if it is not better
1913 /// represented as reg+reg. If Aligned is true, only accept displacements
1914 /// suitable for STD and friends, i.e. multiples of 4.
1915 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1918 bool Aligned) const {
1919 // FIXME dl should come from parent load or store, not from address
1921 // If this can be more profitably realized as r+r, fail.
1922 if (SelectAddressRegReg(N, Disp, Base, DAG))
1925 if (N.getOpcode() == ISD::ADD) {
1927 if (isIntS16Immediate(N.getOperand(1), imm) &&
1928 (!Aligned || (imm & 3) == 0)) {
1929 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1930 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1931 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1932 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1934 Base = N.getOperand(0);
1936 return true; // [r+i]
1937 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1938 // Match LOAD (ADD (X, Lo(G))).
1939 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1940 && "Cannot handle constant offsets yet!");
1941 Disp = N.getOperand(1).getOperand(0); // The global address.
1942 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1943 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1944 Disp.getOpcode() == ISD::TargetConstantPool ||
1945 Disp.getOpcode() == ISD::TargetJumpTable);
1946 Base = N.getOperand(0);
1947 return true; // [&g+r]
1949 } else if (N.getOpcode() == ISD::OR) {
1951 if (isIntS16Immediate(N.getOperand(1), imm) &&
1952 (!Aligned || (imm & 3) == 0)) {
1953 // If this is an or of disjoint bitfields, we can codegen this as an add
1954 // (for better address arithmetic) if the LHS and RHS of the OR are
1955 // provably disjoint.
1956 APInt LHSKnownZero, LHSKnownOne;
1957 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1959 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1960 // If all of the bits are known zero on the LHS or RHS, the add won't
1962 if (FrameIndexSDNode *FI =
1963 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1964 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1965 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1967 Base = N.getOperand(0);
1969 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1973 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1974 // Loading from a constant address.
1976 // If this address fits entirely in a 16-bit sext immediate field, codegen
1979 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1980 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
1981 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1982 CN->getValueType(0));
1986 // Handle 32-bit sext immediates with LIS + addr mode.
1987 if ((CN->getValueType(0) == MVT::i32 ||
1988 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1989 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1990 int Addr = (int)CN->getZExtValue();
1992 // Otherwise, break this down into an LIS + disp.
1993 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
1995 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
1997 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1998 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2003 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2004 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2005 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2006 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2009 return true; // [r+0]
2012 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2013 /// represented as an indexed [r+r] operation.
2014 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2016 SelectionDAG &DAG) const {
2017 // Check to see if we can easily represent this as an [r+r] address. This
2018 // will fail if it thinks that the address is more profitably represented as
2019 // reg+imm, e.g. where imm = 0.
2020 if (SelectAddressRegReg(N, Base, Index, DAG))
2023 // If the operand is an addition, always emit this as [r+r], since this is
2024 // better (for code size, and execution, as the memop does the add for free)
2025 // than emitting an explicit add.
2026 if (N.getOpcode() == ISD::ADD) {
2027 Base = N.getOperand(0);
2028 Index = N.getOperand(1);
2032 // Otherwise, do it the hard way, using R0 as the base register.
2033 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2039 /// getPreIndexedAddressParts - returns true by value, base pointer and
2040 /// offset pointer and addressing mode by reference if the node's address
2041 /// can be legally represented as pre-indexed load / store address.
2042 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2044 ISD::MemIndexedMode &AM,
2045 SelectionDAG &DAG) const {
2046 if (DisablePPCPreinc) return false;
2052 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2053 Ptr = LD->getBasePtr();
2054 VT = LD->getMemoryVT();
2055 Alignment = LD->getAlignment();
2056 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2057 Ptr = ST->getBasePtr();
2058 VT = ST->getMemoryVT();
2059 Alignment = ST->getAlignment();
2064 // PowerPC doesn't have preinc load/store instructions for vectors (except
2065 // for QPX, which does have preinc r+r forms).
2066 if (VT.isVector()) {
2067 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2069 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2075 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2076 // Common code will reject creating a pre-inc form if the base pointer
2077 // is a frame index, or if N is a store and the base pointer is either
2078 // the same as or a predecessor of the value being stored. Check for
2079 // those situations here, and try with swapped Base/Offset instead.
2082 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2085 SDValue Val = cast<StoreSDNode>(N)->getValue();
2086 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2091 std::swap(Base, Offset);
2097 // LDU/STU can only handle immediates that are a multiple of 4.
2098 if (VT != MVT::i64) {
2099 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
2102 // LDU/STU need an address with at least 4-byte alignment.
2106 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
2110 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2111 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
2112 // sext i32 to i64 when addr mode is r+i.
2113 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2114 LD->getExtensionType() == ISD::SEXTLOAD &&
2115 isa<ConstantSDNode>(Offset))
2123 //===----------------------------------------------------------------------===//
2124 // LowerOperation implementation
2125 //===----------------------------------------------------------------------===//
2127 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2128 /// and LoOpFlags to the target MO flags.
2129 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2130 unsigned &HiOpFlags, unsigned &LoOpFlags,
2131 const GlobalValue *GV = nullptr) {
2132 HiOpFlags = PPCII::MO_HA;
2133 LoOpFlags = PPCII::MO_LO;
2135 // Don't use the pic base if not in PIC relocation model.
2137 HiOpFlags |= PPCII::MO_PIC_FLAG;
2138 LoOpFlags |= PPCII::MO_PIC_FLAG;
2141 // If this is a reference to a global value that requires a non-lazy-ptr, make
2142 // sure that instruction lowering adds it.
2143 if (GV && Subtarget.hasLazyResolverStub(GV)) {
2144 HiOpFlags |= PPCII::MO_NLP_FLAG;
2145 LoOpFlags |= PPCII::MO_NLP_FLAG;
2147 if (GV->hasHiddenVisibility()) {
2148 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2149 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2154 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2155 SelectionDAG &DAG) {
2157 EVT PtrVT = HiPart.getValueType();
2158 SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2160 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2161 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2163 // With PIC, the first instruction is actually "GR+hi(&G)".
2165 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2166 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2168 // Generate non-pic code that has direct accesses to the constant pool.
2169 // The address of the global is just (hi(&g)+lo(&g)).
2170 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2173 static void setUsesTOCBasePtr(MachineFunction &MF) {
2174 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2175 FuncInfo->setUsesTOCBasePtr();
2178 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2179 setUsesTOCBasePtr(DAG.getMachineFunction());
2182 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2184 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2185 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2186 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2188 SDValue Ops[] = { GA, Reg };
2189 return DAG.getMemIntrinsicNode(
2190 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2191 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true,
2195 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2196 SelectionDAG &DAG) const {
2197 EVT PtrVT = Op.getValueType();
2198 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2199 const Constant *C = CP->getConstVal();
2201 // 64-bit SVR4 ABI code is always position-independent.
2202 // The actual address of the GlobalValue is stored in the TOC.
2203 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2204 setUsesTOCBasePtr(DAG);
2205 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2206 return getTOCEntry(DAG, SDLoc(CP), true, GA);
2209 unsigned MOHiFlag, MOLoFlag;
2210 bool IsPIC = isPositionIndependent();
2211 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2213 if (IsPIC && Subtarget.isSVR4ABI()) {
2214 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2215 PPCII::MO_PIC_FLAG);
2216 return getTOCEntry(DAG, SDLoc(CP), false, GA);
2220 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2222 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2223 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2226 // For 64-bit PowerPC, prefer the more compact relative encodings.
2227 // This trades 32 bits per jump table entry for one or two instructions
2228 // on the jump site.
2229 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2230 if (isJumpTableRelative())
2231 return MachineJumpTableInfo::EK_LabelDifference32;
2233 return TargetLowering::getJumpTableEncoding();
2236 bool PPCTargetLowering::isJumpTableRelative() const {
2237 if (Subtarget.isPPC64())
2239 return TargetLowering::isJumpTableRelative();
2242 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2243 SelectionDAG &DAG) const {
2244 if (!Subtarget.isPPC64())
2245 return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2247 switch (getTargetMachine().getCodeModel()) {
2248 case CodeModel::Default:
2249 case CodeModel::Small:
2250 case CodeModel::Medium:
2251 return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2253 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2254 getPointerTy(DAG.getDataLayout()));
2259 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2261 MCContext &Ctx) const {
2262 if (!Subtarget.isPPC64())
2263 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2265 switch (getTargetMachine().getCodeModel()) {
2266 case CodeModel::Default:
2267 case CodeModel::Small:
2268 case CodeModel::Medium:
2269 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2271 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2275 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2276 EVT PtrVT = Op.getValueType();
2277 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2279 // 64-bit SVR4 ABI code is always position-independent.
2280 // The actual address of the GlobalValue is stored in the TOC.
2281 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2282 setUsesTOCBasePtr(DAG);
2283 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2284 return getTOCEntry(DAG, SDLoc(JT), true, GA);
2287 unsigned MOHiFlag, MOLoFlag;
2288 bool IsPIC = isPositionIndependent();
2289 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2291 if (IsPIC && Subtarget.isSVR4ABI()) {
2292 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2293 PPCII::MO_PIC_FLAG);
2294 return getTOCEntry(DAG, SDLoc(GA), false, GA);
2297 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2298 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2299 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2302 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2303 SelectionDAG &DAG) const {
2304 EVT PtrVT = Op.getValueType();
2305 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2306 const BlockAddress *BA = BASDN->getBlockAddress();
2308 // 64-bit SVR4 ABI code is always position-independent.
2309 // The actual BlockAddress is stored in the TOC.
2310 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2311 setUsesTOCBasePtr(DAG);
2312 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2313 return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2316 unsigned MOHiFlag, MOLoFlag;
2317 bool IsPIC = isPositionIndependent();
2318 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2319 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2320 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2321 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2324 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2325 SelectionDAG &DAG) const {
2326 // FIXME: TLS addresses currently use medium model code sequences,
2327 // which is the most useful form. Eventually support for small and
2328 // large models could be added if users need it, at the cost of
2329 // additional complexity.
2330 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2331 if (DAG.getTarget().Options.EmulatedTLS)
2332 return LowerToTLSEmulatedModel(GA, DAG);
2335 const GlobalValue *GV = GA->getGlobal();
2336 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2337 bool is64bit = Subtarget.isPPC64();
2338 const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2339 PICLevel::Level picLevel = M->getPICLevel();
2341 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2343 if (Model == TLSModel::LocalExec) {
2344 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2345 PPCII::MO_TPREL_HA);
2346 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2347 PPCII::MO_TPREL_LO);
2348 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2349 is64bit ? MVT::i64 : MVT::i32);
2350 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2351 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2354 if (Model == TLSModel::InitialExec) {
2355 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2356 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2360 setUsesTOCBasePtr(DAG);
2361 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2362 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2363 PtrVT, GOTReg, TGA);
2365 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2366 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2367 PtrVT, TGA, GOTPtr);
2368 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2371 if (Model == TLSModel::GeneralDynamic) {
2372 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2375 setUsesTOCBasePtr(DAG);
2376 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2377 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2380 if (picLevel == PICLevel::SmallPIC)
2381 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2383 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2385 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2389 if (Model == TLSModel::LocalDynamic) {
2390 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2393 setUsesTOCBasePtr(DAG);
2394 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2395 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2398 if (picLevel == PICLevel::SmallPIC)
2399 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2401 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2403 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2404 PtrVT, GOTPtr, TGA, TGA);
2405 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2406 PtrVT, TLSAddr, TGA);
2407 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2410 llvm_unreachable("Unknown TLS model!");
2413 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2414 SelectionDAG &DAG) const {
2415 EVT PtrVT = Op.getValueType();
2416 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2418 const GlobalValue *GV = GSDN->getGlobal();
2420 // 64-bit SVR4 ABI code is always position-independent.
2421 // The actual address of the GlobalValue is stored in the TOC.
2422 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2423 setUsesTOCBasePtr(DAG);
2424 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2425 return getTOCEntry(DAG, DL, true, GA);
2428 unsigned MOHiFlag, MOLoFlag;
2429 bool IsPIC = isPositionIndependent();
2430 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2432 if (IsPIC && Subtarget.isSVR4ABI()) {
2433 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2435 PPCII::MO_PIC_FLAG);
2436 return getTOCEntry(DAG, DL, false, GA);
2440 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2442 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2444 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2446 // If the global reference is actually to a non-lazy-pointer, we have to do an
2447 // extra load to get the address of the global.
2448 if (MOHiFlag & PPCII::MO_NLP_FLAG)
2449 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2453 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2454 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2457 if (Op.getValueType() == MVT::v2i64) {
2458 // When the operands themselves are v2i64 values, we need to do something
2459 // special because VSX has no underlying comparison operations for these.
2460 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2461 // Equality can be handled by casting to the legal type for Altivec
2462 // comparisons, everything else needs to be expanded.
2463 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2464 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2465 DAG.getSetCC(dl, MVT::v4i32,
2466 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2467 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2474 // We handle most of these in the usual way.
2478 // If we're comparing for equality to zero, expose the fact that this is
2479 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2480 // fold the new nodes.
2481 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2484 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2485 // Leave comparisons against 0 and -1 alone for now, since they're usually
2486 // optimized. FIXME: revisit this when we can custom lower all setcc
2488 if (C->isAllOnesValue() || C->isNullValue())
2492 // If we have an integer seteq/setne, turn it into a compare against zero
2493 // by xor'ing the rhs with the lhs, which is faster than setting a
2494 // condition register, reading it back out, and masking the correct bit. The
2495 // normal approach here uses sub to do this instead of xor. Using xor exposes
2496 // the result to other bit-twiddling opportunities.
2497 EVT LHSVT = Op.getOperand(0).getValueType();
2498 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2499 EVT VT = Op.getValueType();
2500 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2502 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2507 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2508 SDNode *Node = Op.getNode();
2509 EVT VT = Node->getValueType(0);
2510 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2511 SDValue InChain = Node->getOperand(0);
2512 SDValue VAListPtr = Node->getOperand(1);
2513 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2516 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2519 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2520 VAListPtr, MachinePointerInfo(SV), MVT::i8);
2521 InChain = GprIndex.getValue(1);
2523 if (VT == MVT::i64) {
2524 // Check if GprIndex is even
2525 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2526 DAG.getConstant(1, dl, MVT::i32));
2527 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2528 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2529 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2530 DAG.getConstant(1, dl, MVT::i32));
2531 // Align GprIndex to be even if it isn't
2532 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2536 // fpr index is 1 byte after gpr
2537 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2538 DAG.getConstant(1, dl, MVT::i32));
2541 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2542 FprPtr, MachinePointerInfo(SV), MVT::i8);
2543 InChain = FprIndex.getValue(1);
2545 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2546 DAG.getConstant(8, dl, MVT::i32));
2548 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2549 DAG.getConstant(4, dl, MVT::i32));
2552 SDValue OverflowArea =
2553 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2554 InChain = OverflowArea.getValue(1);
2556 SDValue RegSaveArea =
2557 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2558 InChain = RegSaveArea.getValue(1);
2560 // select overflow_area if index > 8
2561 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2562 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2564 // adjustment constant gpr_index * 4/8
2565 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2566 VT.isInteger() ? GprIndex : FprIndex,
2567 DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2570 // OurReg = RegSaveArea + RegConstant
2571 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2574 // Floating types are 32 bytes into RegSaveArea
2575 if (VT.isFloatingPoint())
2576 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2577 DAG.getConstant(32, dl, MVT::i32));
2579 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2580 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2581 VT.isInteger() ? GprIndex : FprIndex,
2582 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2585 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2586 VT.isInteger() ? VAListPtr : FprPtr,
2587 MachinePointerInfo(SV), MVT::i8);
2589 // determine if we should load from reg_save_area or overflow_area
2590 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2592 // increase overflow_area by 4/8 if gpr/fpr > 8
2593 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2594 DAG.getConstant(VT.isInteger() ? 4 : 8,
2597 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2600 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
2601 MachinePointerInfo(), MVT::i32);
2603 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
2606 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2607 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2609 // We have to copy the entire va_list struct:
2610 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2611 return DAG.getMemcpy(Op.getOperand(0), Op,
2612 Op.getOperand(1), Op.getOperand(2),
2613 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2614 false, MachinePointerInfo(), MachinePointerInfo());
2617 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2618 SelectionDAG &DAG) const {
2619 return Op.getOperand(0);
2622 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2623 SelectionDAG &DAG) const {
2624 SDValue Chain = Op.getOperand(0);
2625 SDValue Trmp = Op.getOperand(1); // trampoline
2626 SDValue FPtr = Op.getOperand(2); // nested function
2627 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2630 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2631 bool isPPC64 = (PtrVT == MVT::i64);
2632 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2634 TargetLowering::ArgListTy Args;
2635 TargetLowering::ArgListEntry Entry;
2637 Entry.Ty = IntPtrTy;
2638 Entry.Node = Trmp; Args.push_back(Entry);
2640 // TrampSize == (isPPC64 ? 48 : 40);
2641 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2642 isPPC64 ? MVT::i64 : MVT::i32);
2643 Args.push_back(Entry);
2645 Entry.Node = FPtr; Args.push_back(Entry);
2646 Entry.Node = Nest; Args.push_back(Entry);
2648 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2649 TargetLowering::CallLoweringInfo CLI(DAG);
2650 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2651 CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2652 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
2654 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2655 return CallResult.second;
2658 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2659 MachineFunction &MF = DAG.getMachineFunction();
2660 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2661 EVT PtrVT = getPointerTy(MF.getDataLayout());
2665 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2666 // vastart just stores the address of the VarArgsFrameIndex slot into the
2667 // memory location argument.
2668 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2669 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2670 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2671 MachinePointerInfo(SV));
2674 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2675 // We suppose the given va_list is already allocated.
2678 // char gpr; /* index into the array of 8 GPRs
2679 // * stored in the register save area
2680 // * gpr=0 corresponds to r3,
2681 // * gpr=1 to r4, etc.
2683 // char fpr; /* index into the array of 8 FPRs
2684 // * stored in the register save area
2685 // * fpr=0 corresponds to f1,
2686 // * fpr=1 to f2, etc.
2688 // char *overflow_arg_area;
2689 // /* location on stack that holds
2690 // * the next overflow argument
2692 // char *reg_save_area;
2693 // /* where r3:r10 and f1:f8 (if saved)
2698 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2699 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2700 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2702 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2705 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2706 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2708 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2709 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2711 uint64_t FPROffset = 1;
2712 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2714 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2716 // Store first byte : number of int regs
2717 SDValue firstStore =
2718 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
2719 MachinePointerInfo(SV), MVT::i8);
2720 uint64_t nextOffset = FPROffset;
2721 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2724 // Store second byte : number of float regs
2725 SDValue secondStore =
2726 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2727 MachinePointerInfo(SV, nextOffset), MVT::i8);
2728 nextOffset += StackOffset;
2729 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2731 // Store second word : arguments given on stack
2732 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2733 MachinePointerInfo(SV, nextOffset));
2734 nextOffset += FrameOffset;
2735 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2737 // Store third word : arguments given in registers
2738 return DAG.getStore(thirdStore, dl, FR, nextPtr,
2739 MachinePointerInfo(SV, nextOffset));
2742 #include "PPCGenCallingConv.inc"
2744 // Function whose sole purpose is to kill compiler warnings
2745 // stemming from unused functions included from PPCGenCallingConv.inc.
2746 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2747 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2750 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2751 CCValAssign::LocInfo &LocInfo,
2752 ISD::ArgFlagsTy &ArgFlags,
2757 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2759 CCValAssign::LocInfo &LocInfo,
2760 ISD::ArgFlagsTy &ArgFlags,
2762 static const MCPhysReg ArgRegs[] = {
2763 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2764 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2766 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2768 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2770 // Skip one register if the first unallocated register has an even register
2771 // number and there are still argument registers available which have not been
2772 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2773 // need to skip a register if RegNum is odd.
2774 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2775 State.AllocateReg(ArgRegs[RegNum]);
2778 // Always return false here, as this function only makes sure that the first
2779 // unallocated register has an odd register number and does not actually
2780 // allocate a register for the current argument.
2785 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT,
2787 CCValAssign::LocInfo &LocInfo,
2788 ISD::ArgFlagsTy &ArgFlags,
2790 static const MCPhysReg ArgRegs[] = {
2791 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2792 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2794 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2796 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2797 int RegsLeft = NumArgRegs - RegNum;
2799 // Skip if there is not enough registers left for long double type (4 gpr regs
2800 // in soft float mode) and put long double argument on the stack.
2801 if (RegNum != NumArgRegs && RegsLeft < 4) {
2802 for (int i = 0; i < RegsLeft; i++) {
2803 State.AllocateReg(ArgRegs[RegNum + i]);
2810 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2812 CCValAssign::LocInfo &LocInfo,
2813 ISD::ArgFlagsTy &ArgFlags,
2815 static const MCPhysReg ArgRegs[] = {
2816 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2820 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2822 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2824 // If there is only one Floating-point register left we need to put both f64
2825 // values of a split ppc_fp128 value on the stack.
2826 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2827 State.AllocateReg(ArgRegs[RegNum]);
2830 // Always return false here, as this function only makes sure that the two f64
2831 // values a ppc_fp128 value is split into are both passed in registers or both
2832 // passed on the stack and does not actually allocate a register for the
2833 // current argument.
2837 /// FPR - The set of FP registers that should be allocated for arguments,
2839 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5,
2840 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10,
2841 PPC::F11, PPC::F12, PPC::F13};
2843 /// QFPR - The set of QPX registers that should be allocated for arguments.
2844 static const MCPhysReg QFPR[] = {
2845 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7,
2846 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2848 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2850 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2851 unsigned PtrByteSize) {
2852 unsigned ArgSize = ArgVT.getStoreSize();
2853 if (Flags.isByVal())
2854 ArgSize = Flags.getByValSize();
2856 // Round up to multiples of the pointer size, except for array members,
2857 // which are always packed.
2858 if (!Flags.isInConsecutiveRegs())
2859 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2864 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2866 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2867 ISD::ArgFlagsTy Flags,
2868 unsigned PtrByteSize) {
2869 unsigned Align = PtrByteSize;
2871 // Altivec parameters are padded to a 16 byte boundary.
2872 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2873 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2874 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2875 ArgVT == MVT::v1i128)
2877 // QPX vector types stored in double-precision are padded to a 32 byte
2879 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2882 // ByVal parameters are aligned as requested.
2883 if (Flags.isByVal()) {
2884 unsigned BVAlign = Flags.getByValAlign();
2885 if (BVAlign > PtrByteSize) {
2886 if (BVAlign % PtrByteSize != 0)
2888 "ByVal alignment is not a multiple of the pointer size");
2894 // Array members are always packed to their original alignment.
2895 if (Flags.isInConsecutiveRegs()) {
2896 // If the array member was split into multiple registers, the first
2897 // needs to be aligned to the size of the full type. (Except for
2898 // ppcf128, which is only aligned as its f64 components.)
2899 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2900 Align = OrigVT.getStoreSize();
2902 Align = ArgVT.getStoreSize();
2908 /// CalculateStackSlotUsed - Return whether this argument will use its
2909 /// stack slot (instead of being passed in registers). ArgOffset,
2910 /// AvailableFPRs, and AvailableVRs must hold the current argument
2911 /// position, and will be updated to account for this argument.
2912 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2913 ISD::ArgFlagsTy Flags,
2914 unsigned PtrByteSize,
2915 unsigned LinkageSize,
2916 unsigned ParamAreaSize,
2917 unsigned &ArgOffset,
2918 unsigned &AvailableFPRs,
2919 unsigned &AvailableVRs, bool HasQPX) {
2920 bool UseMemory = false;
2922 // Respect alignment of argument on the stack.
2924 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2925 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2926 // If there's no space left in the argument save area, we must
2927 // use memory (this check also catches zero-sized arguments).
2928 if (ArgOffset >= LinkageSize + ParamAreaSize)
2931 // Allocate argument on the stack.
2932 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2933 if (Flags.isInConsecutiveRegsLast())
2934 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2935 // If we overran the argument save area, we must use memory
2936 // (this check catches arguments passed partially in memory)
2937 if (ArgOffset > LinkageSize + ParamAreaSize)
2940 // However, if the argument is actually passed in an FPR or a VR,
2941 // we don't use memory after all.
2942 if (!Flags.isByVal()) {
2943 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2944 // QPX registers overlap with the scalar FP registers.
2945 (HasQPX && (ArgVT == MVT::v4f32 ||
2946 ArgVT == MVT::v4f64 ||
2947 ArgVT == MVT::v4i1)))
2948 if (AvailableFPRs > 0) {
2952 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2953 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2954 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2955 ArgVT == MVT::v1i128)
2956 if (AvailableVRs > 0) {
2965 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2966 /// ensure minimum alignment required for target.
2967 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2968 unsigned NumBytes) {
2969 unsigned TargetAlign = Lowering->getStackAlignment();
2970 unsigned AlignMask = TargetAlign - 1;
2971 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2975 SDValue PPCTargetLowering::LowerFormalArguments(
2976 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2977 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2978 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2979 if (Subtarget.isSVR4ABI()) {
2980 if (Subtarget.isPPC64())
2981 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2984 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2987 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2992 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
2993 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2994 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2995 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2997 // 32-bit SVR4 ABI Stack Frame Layout:
2998 // +-----------------------------------+
2999 // +--> | Back chain |
3000 // | +-----------------------------------+
3001 // | | Floating-point register save area |
3002 // | +-----------------------------------+
3003 // | | General register save area |
3004 // | +-----------------------------------+
3005 // | | CR save word |
3006 // | +-----------------------------------+
3007 // | | VRSAVE save word |
3008 // | +-----------------------------------+
3009 // | | Alignment padding |
3010 // | +-----------------------------------+
3011 // | | Vector register save area |
3012 // | +-----------------------------------+
3013 // | | Local variable space |
3014 // | +-----------------------------------+
3015 // | | Parameter list area |
3016 // | +-----------------------------------+
3017 // | | LR save word |
3018 // | +-----------------------------------+
3019 // SP--> +--- | Back chain |
3020 // +-----------------------------------+
3023 // System V Application Binary Interface PowerPC Processor Supplement
3024 // AltiVec Technology Programming Interface Manual
3026 MachineFunction &MF = DAG.getMachineFunction();
3027 MachineFrameInfo &MFI = MF.getFrameInfo();
3028 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3030 EVT PtrVT = getPointerTy(MF.getDataLayout());
3031 // Potential tail calls could cause overwriting of argument stack slots.
3032 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3033 (CallConv == CallingConv::Fast));
3034 unsigned PtrByteSize = 4;
3036 // Assign locations to all of the incoming arguments.
3037 SmallVector<CCValAssign, 16> ArgLocs;
3038 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3041 // Reserve space for the linkage area on the stack.
3042 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3043 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3045 CCInfo.PreAnalyzeFormalArguments(Ins);
3047 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3048 CCInfo.clearWasPPCF128();
3050 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3051 CCValAssign &VA = ArgLocs[i];
3053 // Arguments stored in registers.
3054 if (VA.isRegLoc()) {
3055 const TargetRegisterClass *RC;
3056 EVT ValVT = VA.getValVT();
3058 switch (ValVT.getSimpleVT().SimpleTy) {
3060 llvm_unreachable("ValVT not supported by formal arguments Lowering");
3063 RC = &PPC::GPRCRegClass;
3066 if (Subtarget.hasP8Vector())
3067 RC = &PPC::VSSRCRegClass;
3069 RC = &PPC::F4RCRegClass;
3072 if (Subtarget.hasVSX())
3073 RC = &PPC::VSFRCRegClass;
3075 RC = &PPC::F8RCRegClass;
3080 RC = &PPC::VRRCRegClass;
3083 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3087 RC = &PPC::VRRCRegClass;
3090 RC = &PPC::QFRCRegClass;
3093 RC = &PPC::QBRCRegClass;
3097 // Transform the arguments stored in physical registers into virtual ones.
3098 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3099 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3100 ValVT == MVT::i1 ? MVT::i32 : ValVT);
3102 if (ValVT == MVT::i1)
3103 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3105 InVals.push_back(ArgValue);
3107 // Argument stored in memory.
3108 assert(VA.isMemLoc());
3110 unsigned ArgSize = VA.getLocVT().getStoreSize();
3111 int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(),
3114 // Create load nodes to retrieve arguments from the stack.
3115 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3117 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3121 // Assign locations to all of the incoming aggregate by value arguments.
3122 // Aggregates passed by value are stored in the local variable space of the
3123 // caller's stack frame, right above the parameter list area.
3124 SmallVector<CCValAssign, 16> ByValArgLocs;
3125 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3126 ByValArgLocs, *DAG.getContext());
3128 // Reserve stack space for the allocations in CCInfo.
3129 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3131 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3133 // Area that is at least reserved in the caller of this function.
3134 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3135 MinReservedArea = std::max(MinReservedArea, LinkageSize);
3137 // Set the size that is at least reserved in caller of this function. Tail
3138 // call optimized function's reserved stack space needs to be aligned so that
3139 // taking the difference between two stack areas will result in an aligned
3142 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3143 FuncInfo->setMinReservedArea(MinReservedArea);
3145 SmallVector<SDValue, 8> MemOps;
3147 // If the function takes variable number of arguments, make a frame index for
3148 // the start of the first vararg value... for expansion of llvm.va_start.
3150 static const MCPhysReg GPArgRegs[] = {
3151 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3152 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3154 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3156 static const MCPhysReg FPArgRegs[] = {
3157 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3160 unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3165 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3166 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3168 // Make room for NumGPArgRegs and NumFPArgRegs.
3169 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3170 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3172 FuncInfo->setVarArgsStackOffset(
3173 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3174 CCInfo.getNextStackOffset(), true));
3176 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3177 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3179 // The fixed integer arguments of a variadic function are stored to the
3180 // VarArgsFrameIndex on the stack so that they may be loaded by
3181 // dereferencing the result of va_next.
3182 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3183 // Get an existing live-in vreg, or add a new one.
3184 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3186 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3188 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3190 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3191 MemOps.push_back(Store);
3192 // Increment the address by four for the next argument to store
3193 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3194 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3197 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3199 // The double arguments are stored to the VarArgsFrameIndex
3201 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3202 // Get an existing live-in vreg, or add a new one.
3203 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3205 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3207 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3209 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3210 MemOps.push_back(Store);
3211 // Increment the address by eight for the next argument to store
3212 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3214 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3218 if (!MemOps.empty())
3219 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3224 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3225 // value to MVT::i64 and then truncate to the correct register size.
3226 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3227 EVT ObjectVT, SelectionDAG &DAG,
3229 const SDLoc &dl) const {
3231 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3232 DAG.getValueType(ObjectVT));
3233 else if (Flags.isZExt())
3234 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3235 DAG.getValueType(ObjectVT));
3237 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3240 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3241 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3242 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3243 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3244 // TODO: add description of PPC stack frame format, or at least some docs.
3246 bool isELFv2ABI = Subtarget.isELFv2ABI();
3247 bool isLittleEndian = Subtarget.isLittleEndian();
3248 MachineFunction &MF = DAG.getMachineFunction();
3249 MachineFrameInfo &MFI = MF.getFrameInfo();
3250 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3252 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3253 "fastcc not supported on varargs functions");
3255 EVT PtrVT = getPointerTy(MF.getDataLayout());
3256 // Potential tail calls could cause overwriting of argument stack slots.
3257 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3258 (CallConv == CallingConv::Fast));
3259 unsigned PtrByteSize = 8;
3260 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3262 static const MCPhysReg GPR[] = {
3263 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3264 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3266 static const MCPhysReg VR[] = {
3267 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3268 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3271 const unsigned Num_GPR_Regs = array_lengthof(GPR);
3272 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3273 const unsigned Num_VR_Regs = array_lengthof(VR);
3274 const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3276 // Do a first pass over the arguments to determine whether the ABI
3277 // guarantees that our caller has allocated the parameter save area
3278 // on its stack frame. In the ELFv1 ABI, this is always the case;
3279 // in the ELFv2 ABI, it is true if this is a vararg function or if
3280 // any parameter is located in a stack slot.
3282 bool HasParameterArea = !isELFv2ABI || isVarArg;
3283 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3284 unsigned NumBytes = LinkageSize;
3285 unsigned AvailableFPRs = Num_FPR_Regs;
3286 unsigned AvailableVRs = Num_VR_Regs;
3287 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3288 if (Ins[i].Flags.isNest())
3291 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3292 PtrByteSize, LinkageSize, ParamAreaSize,
3293 NumBytes, AvailableFPRs, AvailableVRs,
3294 Subtarget.hasQPX()))
3295 HasParameterArea = true;
3298 // Add DAG nodes to load the arguments or copy them out of registers. On
3299 // entry to a function on PPC, the arguments start after the linkage area,
3300 // although the first ones are often in registers.
3302 unsigned ArgOffset = LinkageSize;
3303 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3304 unsigned &QFPR_idx = FPR_idx;
3305 SmallVector<SDValue, 8> MemOps;
3306 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3307 unsigned CurArgIdx = 0;
3308 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3310 bool needsLoad = false;
3311 EVT ObjectVT = Ins[ArgNo].VT;
3312 EVT OrigVT = Ins[ArgNo].ArgVT;
3313 unsigned ObjSize = ObjectVT.getStoreSize();
3314 unsigned ArgSize = ObjSize;
3315 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3316 if (Ins[ArgNo].isOrigArg()) {
3317 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3318 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3320 // We re-align the argument offset for each argument, except when using the
3321 // fast calling convention, when we need to make sure we do that only when
3322 // we'll actually use a stack slot.
3323 unsigned CurArgOffset, Align;
3324 auto ComputeArgOffset = [&]() {
3325 /* Respect alignment of argument on the stack. */
3326 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3327 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3328 CurArgOffset = ArgOffset;
3331 if (CallConv != CallingConv::Fast) {
3334 /* Compute GPR index associated with argument offset. */
3335 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3336 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3339 // FIXME the codegen can be much improved in some cases.
3340 // We do not have to keep everything in memory.
3341 if (Flags.isByVal()) {
3342 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3344 if (CallConv == CallingConv::Fast)
3347 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3348 ObjSize = Flags.getByValSize();
3349 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3350 // Empty aggregate parameters do not take up registers. Examples:
3354 // etc. However, we have to provide a place-holder in InVals, so
3355 // pretend we have an 8-byte item at the current address for that
3358 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3359 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3360 InVals.push_back(FIN);
3364 // Create a stack object covering all stack doublewords occupied
3365 // by the argument. If the argument is (fully or partially) on
3366 // the stack, or if the argument is fully in registers but the
3367 // caller has allocated the parameter save anyway, we can refer
3368 // directly to the caller's stack frame. Otherwise, create a
3369 // local copy in our own frame.
3371 if (HasParameterArea ||
3372 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3373 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3375 FI = MFI.CreateStackObject(ArgSize, Align, false);
3376 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3378 // Handle aggregates smaller than 8 bytes.
3379 if (ObjSize < PtrByteSize) {
3380 // The value of the object is its address, which differs from the
3381 // address of the enclosing doubleword on big-endian systems.
3383 if (!isLittleEndian) {
3384 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3385 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3387 InVals.push_back(Arg);
3389 if (GPR_idx != Num_GPR_Regs) {
3390 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3391 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3394 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3395 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3396 (ObjSize == 2 ? MVT::i16 : MVT::i32));
3397 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3398 MachinePointerInfo(&*FuncArg), ObjType);
3400 // For sizes that don't fit a truncating store (3, 5, 6, 7),
3401 // store the whole register as-is to the parameter save area
3403 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3404 MachinePointerInfo(&*FuncArg));
3407 MemOps.push_back(Store);
3409 // Whether we copied from a register or not, advance the offset
3410 // into the parameter save area by a full doubleword.
3411 ArgOffset += PtrByteSize;
3415 // The value of the object is its address, which is the address of
3416 // its first stack doubleword.
3417 InVals.push_back(FIN);
3419 // Store whatever pieces of the object are in registers to memory.
3420 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3421 if (GPR_idx == Num_GPR_Regs)
3424 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3425 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3428 SDValue Off = DAG.getConstant(j, dl, PtrVT);
3429 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3431 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3432 MachinePointerInfo(&*FuncArg, j));
3433 MemOps.push_back(Store);
3436 ArgOffset += ArgSize;
3440 switch (ObjectVT.getSimpleVT().SimpleTy) {
3441 default: llvm_unreachable("Unhandled argument type!");
3445 if (Flags.isNest()) {
3446 // The 'nest' parameter, if any, is passed in R11.
3447 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3448 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3450 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3451 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3456 // These can be scalar arguments or elements of an integer array type
3457 // passed directly. Clang may use those instead of "byval" aggregate
3458 // types to avoid forcing arguments to memory unnecessarily.
3459 if (GPR_idx != Num_GPR_Regs) {
3460 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3461 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3463 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3464 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3465 // value to MVT::i64 and then truncate to the correct register size.
3466 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3468 if (CallConv == CallingConv::Fast)
3472 ArgSize = PtrByteSize;
3474 if (CallConv != CallingConv::Fast || needsLoad)
3480 // These can be scalar arguments or elements of a float array type
3481 // passed directly. The latter are used to implement ELFv2 homogenous
3482 // float aggregates.
3483 if (FPR_idx != Num_FPR_Regs) {
3486 if (ObjectVT == MVT::f32)
3487 VReg = MF.addLiveIn(FPR[FPR_idx],
3488 Subtarget.hasP8Vector()
3489 ? &PPC::VSSRCRegClass
3490 : &PPC::F4RCRegClass);
3492 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3493 ? &PPC::VSFRCRegClass
3494 : &PPC::F8RCRegClass);
3496 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3498 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3499 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3500 // once we support fp <-> gpr moves.
3502 // This can only ever happen in the presence of f32 array types,
3503 // since otherwise we never run out of FPRs before running out
3505 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3506 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3508 if (ObjectVT == MVT::f32) {
3509 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3510 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3511 DAG.getConstant(32, dl, MVT::i32));
3512 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3515 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3517 if (CallConv == CallingConv::Fast)
3523 // When passing an array of floats, the array occupies consecutive
3524 // space in the argument area; only round up to the next doubleword
3525 // at the end of the array. Otherwise, each float takes 8 bytes.
3526 if (CallConv != CallingConv::Fast || needsLoad) {
3527 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3528 ArgOffset += ArgSize;
3529 if (Flags.isInConsecutiveRegsLast())
3530 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3540 if (!Subtarget.hasQPX()) {
3541 // These can be scalar arguments or elements of a vector array type
3542 // passed directly. The latter are used to implement ELFv2 homogenous
3543 // vector aggregates.
3544 if (VR_idx != Num_VR_Regs) {
3545 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3546 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3549 if (CallConv == CallingConv::Fast)
3554 if (CallConv != CallingConv::Fast || needsLoad)
3559 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3560 "Invalid QPX parameter type");
3565 // QPX vectors are treated like their scalar floating-point subregisters
3566 // (except that they're larger).
3567 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3568 if (QFPR_idx != Num_QFPR_Regs) {
3569 const TargetRegisterClass *RC;
3570 switch (ObjectVT.getSimpleVT().SimpleTy) {
3571 case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3572 case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3573 default: RC = &PPC::QBRCRegClass; break;
3576 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3577 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3580 if (CallConv == CallingConv::Fast)
3584 if (CallConv != CallingConv::Fast || needsLoad)
3589 // We need to load the argument to a virtual register if we determined
3590 // above that we ran out of physical registers of the appropriate type.
3592 if (ObjSize < ArgSize && !isLittleEndian)
3593 CurArgOffset += ArgSize - ObjSize;
3594 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3595 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3596 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3599 InVals.push_back(ArgVal);
3602 // Area that is at least reserved in the caller of this function.
3603 unsigned MinReservedArea;
3604 if (HasParameterArea)
3605 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3607 MinReservedArea = LinkageSize;
3609 // Set the size that is at least reserved in caller of this function. Tail
3610 // call optimized functions' reserved stack space needs to be aligned so that
3611 // taking the difference between two stack areas will result in an aligned
3614 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3615 FuncInfo->setMinReservedArea(MinReservedArea);
3617 // If the function takes variable number of arguments, make a frame index for
3618 // the start of the first vararg value... for expansion of llvm.va_start.
3620 int Depth = ArgOffset;
3622 FuncInfo->setVarArgsFrameIndex(
3623 MFI.CreateFixedObject(PtrByteSize, Depth, true));
3624 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3626 // If this function is vararg, store any remaining integer argument regs
3627 // to their spots on the stack so that they may be loaded by dereferencing
3628 // the result of va_next.
3629 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3630 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3631 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3632 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3634 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3635 MemOps.push_back(Store);
3636 // Increment the address by four for the next argument to store
3637 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3638 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3642 if (!MemOps.empty())
3643 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3648 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
3649 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3650 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3651 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3652 // TODO: add description of PPC stack frame format, or at least some docs.
3654 MachineFunction &MF = DAG.getMachineFunction();
3655 MachineFrameInfo &MFI = MF.getFrameInfo();
3656 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3658 EVT PtrVT = getPointerTy(MF.getDataLayout());
3659 bool isPPC64 = PtrVT == MVT::i64;
3660 // Potential tail calls could cause overwriting of argument stack slots.
3661 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3662 (CallConv == CallingConv::Fast));
3663 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3664 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3665 unsigned ArgOffset = LinkageSize;
3666 // Area that is at least reserved in caller of this function.
3667 unsigned MinReservedArea = ArgOffset;
3669 static const MCPhysReg GPR_32[] = { // 32-bit registers.
3670 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3671 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3673 static const MCPhysReg GPR_64[] = { // 64-bit registers.
3674 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3675 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3677 static const MCPhysReg VR[] = {
3678 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3679 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3682 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3683 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3684 const unsigned Num_VR_Regs = array_lengthof( VR);
3686 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3688 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3690 // In 32-bit non-varargs functions, the stack space for vectors is after the
3691 // stack space for non-vectors. We do not use this space unless we have
3692 // too many vectors to fit in registers, something that only occurs in
3693 // constructed examples:), but we have to walk the arglist to figure
3694 // that out...for the pathological case, compute VecArgOffset as the
3695 // start of the vector parameter area. Computing VecArgOffset is the
3696 // entire point of the following loop.
3697 unsigned VecArgOffset = ArgOffset;
3698 if (!isVarArg && !isPPC64) {
3699 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3701 EVT ObjectVT = Ins[ArgNo].VT;
3702 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3704 if (Flags.isByVal()) {
3705 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3706 unsigned ObjSize = Flags.getByValSize();
3708 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3709 VecArgOffset += ArgSize;
3713 switch(ObjectVT.getSimpleVT().SimpleTy) {
3714 default: llvm_unreachable("Unhandled argument type!");
3720 case MVT::i64: // PPC64
3722 // FIXME: We are guaranteed to be !isPPC64 at this point.
3723 // Does MVT::i64 apply?
3730 // Nothing to do, we're only looking at Nonvector args here.
3735 // We've found where the vector parameter area in memory is. Skip the
3736 // first 12 parameters; these don't use that memory.
3737 VecArgOffset = ((VecArgOffset+15)/16)*16;
3738 VecArgOffset += 12*16;
3740 // Add DAG nodes to load the arguments or copy them out of registers. On
3741 // entry to a function on PPC, the arguments start after the linkage area,
3742 // although the first ones are often in registers.
3744 SmallVector<SDValue, 8> MemOps;
3745 unsigned nAltivecParamsAtEnd = 0;
3746 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3747 unsigned CurArgIdx = 0;
3748 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3750 bool needsLoad = false;
3751 EVT ObjectVT = Ins[ArgNo].VT;
3752 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3753 unsigned ArgSize = ObjSize;
3754 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3755 if (Ins[ArgNo].isOrigArg()) {
3756 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3757 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3759 unsigned CurArgOffset = ArgOffset;
3761 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3762 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3763 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3764 if (isVarArg || isPPC64) {
3765 MinReservedArea = ((MinReservedArea+15)/16)*16;
3766 MinReservedArea += CalculateStackSlotSize(ObjectVT,
3769 } else nAltivecParamsAtEnd++;
3771 // Calculate min reserved area.
3772 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3776 // FIXME the codegen can be much improved in some cases.
3777 // We do not have to keep everything in memory.
3778 if (Flags.isByVal()) {
3779 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3781 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3782 ObjSize = Flags.getByValSize();
3783 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3784 // Objects of size 1 and 2 are right justified, everything else is
3785 // left justified. This means the memory address is adjusted forwards.
3786 if (ObjSize==1 || ObjSize==2) {
3787 CurArgOffset = CurArgOffset + (4 - ObjSize);
3789 // The value of the object is its address.
3790 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
3791 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3792 InVals.push_back(FIN);
3793 if (ObjSize==1 || ObjSize==2) {
3794 if (GPR_idx != Num_GPR_Regs) {
3797 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3799 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3800 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3801 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3803 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3804 MachinePointerInfo(&*FuncArg), ObjType);
3805 MemOps.push_back(Store);
3809 ArgOffset += PtrByteSize;
3813 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3814 // Store whatever pieces of the object are in registers
3815 // to memory. ArgOffset will be the address of the beginning
3817 if (GPR_idx != Num_GPR_Regs) {
3820 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3822 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3823 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3824 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3825 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3826 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3827 MachinePointerInfo(&*FuncArg, j));
3828 MemOps.push_back(Store);
3830 ArgOffset += PtrByteSize;
3832 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3839 switch (ObjectVT.getSimpleVT().SimpleTy) {
3840 default: llvm_unreachable("Unhandled argument type!");
3844 if (GPR_idx != Num_GPR_Regs) {
3845 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3846 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3848 if (ObjectVT == MVT::i1)
3849 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3854 ArgSize = PtrByteSize;
3856 // All int arguments reserve stack space in the Darwin ABI.
3857 ArgOffset += PtrByteSize;
3861 case MVT::i64: // PPC64
3862 if (GPR_idx != Num_GPR_Regs) {
3863 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3864 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3866 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3867 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3868 // value to MVT::i64 and then truncate to the correct register size.
3869 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3874 ArgSize = PtrByteSize;
3876 // All int arguments reserve stack space in the Darwin ABI.
3882 // Every 4 bytes of argument space consumes one of the GPRs available for
3883 // argument passing.
3884 if (GPR_idx != Num_GPR_Regs) {
3886 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3889 if (FPR_idx != Num_FPR_Regs) {
3892 if (ObjectVT == MVT::f32)
3893 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3895 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3897 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3903 // All FP arguments reserve stack space in the Darwin ABI.
3904 ArgOffset += isPPC64 ? 8 : ObjSize;
3910 // Note that vector arguments in registers don't reserve stack space,
3911 // except in varargs functions.
3912 if (VR_idx != Num_VR_Regs) {
3913 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3914 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3916 while ((ArgOffset % 16) != 0) {
3917 ArgOffset += PtrByteSize;
3918 if (GPR_idx != Num_GPR_Regs)
3922 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3926 if (!isVarArg && !isPPC64) {
3927 // Vectors go after all the nonvectors.
3928 CurArgOffset = VecArgOffset;
3931 // Vectors are aligned.
3932 ArgOffset = ((ArgOffset+15)/16)*16;
3933 CurArgOffset = ArgOffset;
3941 // We need to load the argument to a virtual register if we determined above
3942 // that we ran out of physical registers of the appropriate type.
3944 int FI = MFI.CreateFixedObject(ObjSize,
3945 CurArgOffset + (ArgSize - ObjSize),
3947 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3948 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3951 InVals.push_back(ArgVal);
3954 // Allow for Altivec parameters at the end, if needed.
3955 if (nAltivecParamsAtEnd) {
3956 MinReservedArea = ((MinReservedArea+15)/16)*16;
3957 MinReservedArea += 16*nAltivecParamsAtEnd;
3960 // Area that is at least reserved in the caller of this function.
3961 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3963 // Set the size that is at least reserved in caller of this function. Tail
3964 // call optimized functions' reserved stack space needs to be aligned so that
3965 // taking the difference between two stack areas will result in an aligned
3968 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3969 FuncInfo->setMinReservedArea(MinReservedArea);
3971 // If the function takes variable number of arguments, make a frame index for
3972 // the start of the first vararg value... for expansion of llvm.va_start.
3974 int Depth = ArgOffset;
3976 FuncInfo->setVarArgsFrameIndex(
3977 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3979 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3981 // If this function is vararg, store any remaining integer argument regs
3982 // to their spots on the stack so that they may be loaded by dereferencing
3983 // the result of va_next.
3984 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3988 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3990 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3992 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3994 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3995 MemOps.push_back(Store);
3996 // Increment the address by four for the next argument to store
3997 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3998 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4002 if (!MemOps.empty())
4003 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4008 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4009 /// adjusted to accommodate the arguments for the tailcall.
4010 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4011 unsigned ParamSize) {
4013 if (!isTailCall) return 0;
4015 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4016 unsigned CallerMinReservedArea = FI->getMinReservedArea();
4017 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4018 // Remember only if the new adjustement is bigger.
4019 if (SPDiff < FI->getTailCallSPDelta())
4020 FI->setTailCallSPDelta(SPDiff);
4025 static bool isFunctionGlobalAddress(SDValue Callee);
4028 resideInSameSection(const Function *Caller, SDValue Callee,
4029 const TargetMachine &TM) {
4030 // If !G, Callee can be an external symbol.
4031 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4035 const GlobalValue *GV = G->getGlobal();
4036 if (!GV->isStrongDefinitionForLinker())
4039 // Any explicitly-specified sections and section prefixes must also match.
4040 // Also, if we're using -ffunction-sections, then each function is always in
4041 // a different section (the same is true for COMDAT functions).
4042 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4043 GV->getSection() != Caller->getSection())
4045 if (const auto *F = dyn_cast<Function>(GV)) {
4046 if (F->getSectionPrefix() != Caller->getSectionPrefix())
4050 // If the callee might be interposed, then we can't assume the ultimate call
4051 // target will be in the same section. Even in cases where we can assume that
4052 // interposition won't happen, in any case where the linker might insert a
4053 // stub to allow for interposition, we must generate code as though
4054 // interposition might occur. To understand why this matters, consider a
4055 // situation where: a -> b -> c where the arrows indicate calls. b and c are
4056 // in the same section, but a is in a different module (i.e. has a different
4057 // TOC base pointer). If the linker allows for interposition between b and c,
4058 // then it will generate a stub for the call edge between b and c which will
4059 // save the TOC pointer into the designated stack slot allocated by b. If we
4060 // return true here, and therefore allow a tail call between b and c, that
4061 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4062 // pointer into the stack slot allocated by a (where the a -> b stub saved
4063 // a's TOC base pointer). If we're not considering a tail call, but rather,
4064 // whether a nop is needed after the call instruction in b, because the linker
4065 // will insert a stub, it might complain about a missing nop if we omit it
4066 // (although many don't complain in this case).
4067 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4074 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4075 const SmallVectorImpl<ISD::OutputArg> &Outs) {
4076 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
4078 const unsigned PtrByteSize = 8;
4079 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4081 static const MCPhysReg GPR[] = {
4082 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4083 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4085 static const MCPhysReg VR[] = {
4086 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4087 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4090 const unsigned NumGPRs = array_lengthof(GPR);
4091 const unsigned NumFPRs = 13;
4092 const unsigned NumVRs = array_lengthof(VR);
4093 const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4095 unsigned NumBytes = LinkageSize;
4096 unsigned AvailableFPRs = NumFPRs;
4097 unsigned AvailableVRs = NumVRs;
4099 for (const ISD::OutputArg& Param : Outs) {
4100 if (Param.Flags.isNest()) continue;
4102 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4103 PtrByteSize, LinkageSize, ParamAreaSize,
4104 NumBytes, AvailableFPRs, AvailableVRs,
4105 Subtarget.hasQPX()))
4112 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite *CS) {
4113 if (CS->arg_size() != CallerFn->arg_size())
4116 ImmutableCallSite::arg_iterator CalleeArgIter = CS->arg_begin();
4117 ImmutableCallSite::arg_iterator CalleeArgEnd = CS->arg_end();
4118 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4120 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4121 const Value* CalleeArg = *CalleeArgIter;
4122 const Value* CallerArg = &(*CallerArgIter);
4123 if (CalleeArg == CallerArg)
4126 // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4127 // tail call @callee([4 x i64] undef, [4 x i64] %b)
4129 // 1st argument of callee is undef and has the same type as caller.
4130 if (CalleeArg->getType() == CallerArg->getType() &&
4131 isa<UndefValue>(CalleeArg))
4141 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4143 CallingConv::ID CalleeCC,
4144 ImmutableCallSite *CS,
4146 const SmallVectorImpl<ISD::OutputArg> &Outs,
4147 const SmallVectorImpl<ISD::InputArg> &Ins,
4148 SelectionDAG& DAG) const {
4149 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4151 if (DisableSCO && !TailCallOpt) return false;
4153 // Variadic argument functions are not supported.
4154 if (isVarArg) return false;
4156 MachineFunction &MF = DAG.getMachineFunction();
4157 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4159 // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has
4160 // the same calling convention
4161 if (CallerCC != CalleeCC) return false;
4163 // SCO support C calling convention
4164 if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C)
4167 // Caller contains any byval parameter is not supported.
4168 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4171 // Callee contains any byval parameter is not supported, too.
4172 // Note: This is a quick work around, because in some cases, e.g.
4173 // caller's stack size > callee's stack size, we are still able to apply
4174 // sibling call optimization. See: https://reviews.llvm.org/D23441#513574
4175 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4178 // No TCO/SCO on indirect call because Caller have to restore its TOC
4179 if (!isFunctionGlobalAddress(Callee) &&
4180 !isa<ExternalSymbolSDNode>(Callee))
4183 // Check if Callee resides in the same section, because for now, PPC64 SVR4
4184 // ABI (ELFv1/ELFv2) doesn't allow tail calls to a symbol resides in another
4186 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4187 if (!resideInSameSection(MF.getFunction(), Callee, getTargetMachine()))
4190 // TCO allows altering callee ABI, so we don't have to check further.
4191 if (CalleeCC == CallingConv::Fast && TailCallOpt)
4194 if (DisableSCO) return false;
4196 // If callee use the same argument list that caller is using, then we can
4197 // apply SCO on this case. If it is not, then we need to check if callee needs
4198 // stack for passing arguments.
4199 if (!hasSameArgumentList(MF.getFunction(), CS) &&
4200 needStackSlotPassParameters(Subtarget, Outs)) {
4207 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4208 /// for tail call optimization. Targets which want to do tail call
4209 /// optimization should implement this function.
4211 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4212 CallingConv::ID CalleeCC,
4214 const SmallVectorImpl<ISD::InputArg> &Ins,
4215 SelectionDAG& DAG) const {
4216 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4219 // Variable argument functions are not supported.
4223 MachineFunction &MF = DAG.getMachineFunction();
4224 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4225 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4226 // Functions containing by val parameters are not supported.
4227 for (unsigned i = 0; i != Ins.size(); i++) {
4228 ISD::ArgFlagsTy Flags = Ins[i].Flags;
4229 if (Flags.isByVal()) return false;
4232 // Non-PIC/GOT tail calls are supported.
4233 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4236 // At the moment we can only do local tail calls (in same module, hidden
4237 // or protected) if we are generating PIC.
4238 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4239 return G->getGlobal()->hasHiddenVisibility()
4240 || G->getGlobal()->hasProtectedVisibility();
4246 /// isCallCompatibleAddress - Return the immediate to use if the specified
4247 /// 32-bit value is representable in the immediate field of a BxA instruction.
4248 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4249 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4250 if (!C) return nullptr;
4252 int Addr = C->getZExtValue();
4253 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
4254 SignExtend32<26>(Addr) != Addr)
4255 return nullptr; // Top 6 bits have to be sext of immediate.
4259 (int)C->getZExtValue() >> 2, SDLoc(Op),
4260 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4266 struct TailCallArgumentInfo {
4271 TailCallArgumentInfo() = default;
4274 } // end anonymous namespace
4276 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4277 static void StoreTailCallArgumentsToStackSlot(
4278 SelectionDAG &DAG, SDValue Chain,
4279 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4280 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4281 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4282 SDValue Arg = TailCallArgs[i].Arg;
4283 SDValue FIN = TailCallArgs[i].FrameIdxOp;
4284 int FI = TailCallArgs[i].FrameIdx;
4285 // Store relative to framepointer.
4286 MemOpChains.push_back(DAG.getStore(
4287 Chain, dl, Arg, FIN,
4288 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4292 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4293 /// the appropriate stack slot for the tail call optimized function call.
4294 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4295 SDValue OldRetAddr, SDValue OldFP,
4296 int SPDiff, const SDLoc &dl) {
4298 // Calculate the new stack slot for the return address.
4299 MachineFunction &MF = DAG.getMachineFunction();
4300 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4301 const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4302 bool isPPC64 = Subtarget.isPPC64();
4303 int SlotSize = isPPC64 ? 8 : 4;
4304 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4305 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4306 NewRetAddrLoc, true);
4307 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4308 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4309 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4310 MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4312 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4313 // slot as the FP is never overwritten.
4314 if (Subtarget.isDarwinABI()) {
4315 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4316 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4318 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4319 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4320 MachinePointerInfo::getFixedStack(
4321 DAG.getMachineFunction(), NewFPIdx));
4327 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4328 /// the position of the argument.
4330 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4331 SDValue Arg, int SPDiff, unsigned ArgOffset,
4332 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4333 int Offset = ArgOffset + SPDiff;
4334 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4335 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4336 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4337 SDValue FIN = DAG.getFrameIndex(FI, VT);
4338 TailCallArgumentInfo Info;
4340 Info.FrameIdxOp = FIN;
4342 TailCallArguments.push_back(Info);
4345 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4346 /// stack slot. Returns the chain as result and the loaded frame pointers in
4347 /// LROpOut/FPOpout. Used when tail calling.
4348 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4349 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4350 SDValue &FPOpOut, const SDLoc &dl) const {
4352 // Load the LR and FP stack slot for later adjusting.
4353 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4354 LROpOut = getReturnAddrFrameIndex(DAG);
4355 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4356 Chain = SDValue(LROpOut.getNode(), 1);
4358 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4359 // slot as the FP is never overwritten.
4360 if (Subtarget.isDarwinABI()) {
4361 FPOpOut = getFramePointerFrameIndex(DAG);
4362 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4363 Chain = SDValue(FPOpOut.getNode(), 1);
4369 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4370 /// by "Src" to address "Dst" of size "Size". Alignment information is
4371 /// specified by the specific parameter attribute. The copy will be passed as
4372 /// a byval function parameter.
4373 /// Sometimes what we are copying is the end of a larger object, the part that
4374 /// does not fit in registers.
4375 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4376 SDValue Chain, ISD::ArgFlagsTy Flags,
4377 SelectionDAG &DAG, const SDLoc &dl) {
4378 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4379 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4380 false, false, false, MachinePointerInfo(),
4381 MachinePointerInfo());
4384 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4386 static void LowerMemOpCallTo(
4387 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4388 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4389 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4390 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4391 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4396 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4398 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4399 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4400 DAG.getConstant(ArgOffset, dl, PtrVT));
4402 MemOpChains.push_back(
4403 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4404 // Calculate and remember argument location.
4405 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4410 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4411 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4413 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4414 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4415 // might overwrite each other in case of tail call optimization.
4416 SmallVector<SDValue, 8> MemOpChains2;
4417 // Do not flag preceding copytoreg stuff together with the following stuff.
4419 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4421 if (!MemOpChains2.empty())
4422 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4424 // Store the return address to the appropriate stack slot.
4425 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4427 // Emit callseq_end just before tailcall node.
4428 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4429 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4430 InFlag = Chain.getValue(1);
4433 // Is this global address that of a function that can be called by name? (as
4434 // opposed to something that must hold a descriptor for an indirect call).
4435 static bool isFunctionGlobalAddress(SDValue Callee) {
4436 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4437 if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4438 Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4441 return G->getGlobal()->getValueType()->isFunctionTy();
4448 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4449 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4450 bool isPatchPoint, bool hasNest,
4451 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4452 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4453 ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
4454 bool isPPC64 = Subtarget.isPPC64();
4455 bool isSVR4ABI = Subtarget.isSVR4ABI();
4456 bool isELFv2ABI = Subtarget.isELFv2ABI();
4458 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4459 NodeTys.push_back(MVT::Other); // Returns a chain
4460 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
4462 unsigned CallOpc = PPCISD::CALL;
4464 bool needIndirectCall = true;
4465 if (!isSVR4ABI || !isPPC64)
4466 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4467 // If this is an absolute destination address, use the munged value.
4468 Callee = SDValue(Dest, 0);
4469 needIndirectCall = false;
4472 // PC-relative references to external symbols should go through $stub, unless
4473 // we're building with the leopard linker or later, which automatically
4474 // synthesizes these stubs.
4475 const TargetMachine &TM = DAG.getTarget();
4476 const Module *Mod = DAG.getMachineFunction().getFunction()->getParent();
4477 const GlobalValue *GV = nullptr;
4478 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4479 GV = G->getGlobal();
4480 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4481 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4483 if (isFunctionGlobalAddress(Callee)) {
4484 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4485 // A call to a TLS address is actually an indirect call to a
4486 // thread-specific pointer.
4487 unsigned OpFlags = 0;
4489 OpFlags = PPCII::MO_PLT;
4491 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4492 // every direct call is) turn it into a TargetGlobalAddress /
4493 // TargetExternalSymbol node so that legalize doesn't hack it.
4494 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4495 Callee.getValueType(), 0, OpFlags);
4496 needIndirectCall = false;
4499 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4500 unsigned char OpFlags = 0;
4503 OpFlags = PPCII::MO_PLT;
4505 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4507 needIndirectCall = false;
4511 // We'll form an invalid direct call when lowering a patchpoint; the full
4512 // sequence for an indirect call is complicated, and many of the
4513 // instructions introduced might have side effects (and, thus, can't be
4514 // removed later). The call itself will be removed as soon as the
4515 // argument/return lowering is complete, so the fact that it has the wrong
4516 // kind of operands should not really matter.
4517 needIndirectCall = false;
4520 if (needIndirectCall) {
4521 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
4522 // to do the call, we can't use PPCISD::CALL.
4523 SDValue MTCTROps[] = {Chain, Callee, InFlag};
4525 if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4526 // Function pointers in the 64-bit SVR4 ABI do not point to the function
4527 // entry point, but to the function descriptor (the function entry point
4528 // address is part of the function descriptor though).
4529 // The function descriptor is a three doubleword structure with the
4530 // following fields: function entry point, TOC base address and
4531 // environment pointer.
4532 // Thus for a call through a function pointer, the following actions need
4534 // 1. Save the TOC of the caller in the TOC save area of its stack
4535 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4536 // 2. Load the address of the function entry point from the function
4538 // 3. Load the TOC of the callee from the function descriptor into r2.
4539 // 4. Load the environment pointer from the function descriptor into
4541 // 5. Branch to the function entry point address.
4542 // 6. On return of the callee, the TOC of the caller needs to be
4543 // restored (this is done in FinishCall()).
4545 // The loads are scheduled at the beginning of the call sequence, and the
4546 // register copies are flagged together to ensure that no other
4547 // operations can be scheduled in between. E.g. without flagging the
4548 // copies together, a TOC access in the caller could be scheduled between
4549 // the assignment of the callee TOC and the branch to the callee, which
4550 // results in the TOC access going through the TOC of the callee instead
4551 // of going through the TOC of the caller, which leads to incorrect code.
4553 // Load the address of the function entry point from the function
4555 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4556 if (LDChain.getValueType() == MVT::Glue)
4557 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4559 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
4560 ? (MachineMemOperand::MODereferenceable |
4561 MachineMemOperand::MOInvariant)
4562 : MachineMemOperand::MONone;
4564 MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4565 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4566 /* Alignment = */ 8, MMOFlags);
4568 // Load environment pointer into r11.
4569 SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4570 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4571 SDValue LoadEnvPtr =
4572 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
4573 /* Alignment = */ 8, MMOFlags);
4575 SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4576 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4578 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
4579 /* Alignment = */ 8, MMOFlags);
4581 setUsesTOCBasePtr(DAG);
4582 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4584 Chain = TOCVal.getValue(0);
4585 InFlag = TOCVal.getValue(1);
4587 // If the function call has an explicit 'nest' parameter, it takes the
4588 // place of the environment pointer.
4590 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4593 Chain = EnvVal.getValue(0);
4594 InFlag = EnvVal.getValue(1);
4597 MTCTROps[0] = Chain;
4598 MTCTROps[1] = LoadFuncPtr;
4599 MTCTROps[2] = InFlag;
4602 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4603 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4604 InFlag = Chain.getValue(1);
4607 NodeTys.push_back(MVT::Other);
4608 NodeTys.push_back(MVT::Glue);
4609 Ops.push_back(Chain);
4610 CallOpc = PPCISD::BCTRL;
4611 Callee.setNode(nullptr);
4612 // Add use of X11 (holding environment pointer)
4613 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4614 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4615 // Add CTR register as callee so a bctr can be emitted later.
4617 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4620 // If this is a direct call, pass the chain and the callee.
4621 if (Callee.getNode()) {
4622 Ops.push_back(Chain);
4623 Ops.push_back(Callee);
4625 // If this is a tail call add stack pointer delta.
4627 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4629 // Add argument registers to the end of the list so that they are known live
4631 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4632 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4633 RegsToPass[i].second.getValueType()));
4635 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4637 if (isSVR4ABI && isPPC64 && !isPatchPoint) {
4638 setUsesTOCBasePtr(DAG);
4639 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4645 SDValue PPCTargetLowering::LowerCallResult(
4646 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4647 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4648 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4649 SmallVector<CCValAssign, 16> RVLocs;
4650 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4652 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4654 // Copy all of the result registers out of their specified physreg.
4655 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4656 CCValAssign &VA = RVLocs[i];
4657 assert(VA.isRegLoc() && "Can only return in registers!");
4659 SDValue Val = DAG.getCopyFromReg(Chain, dl,
4660 VA.getLocReg(), VA.getLocVT(), InFlag);
4661 Chain = Val.getValue(1);
4662 InFlag = Val.getValue(2);
4664 switch (VA.getLocInfo()) {
4665 default: llvm_unreachable("Unknown loc info!");
4666 case CCValAssign::Full: break;
4667 case CCValAssign::AExt:
4668 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4670 case CCValAssign::ZExt:
4671 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4672 DAG.getValueType(VA.getValVT()));
4673 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4675 case CCValAssign::SExt:
4676 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4677 DAG.getValueType(VA.getValVT()));
4678 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4682 InVals.push_back(Val);
4688 SDValue PPCTargetLowering::FinishCall(
4689 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
4690 bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
4691 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
4692 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
4693 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
4694 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const {
4695 std::vector<EVT> NodeTys;
4696 SmallVector<SDValue, 8> Ops;
4697 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4698 SPDiff, isTailCall, isPatchPoint, hasNest,
4699 RegsToPass, Ops, NodeTys, CS, Subtarget);
4701 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4702 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4703 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4705 // When performing tail call optimization the callee pops its arguments off
4706 // the stack. Account for this here so these bytes can be pushed back on in
4707 // PPCFrameLowering::eliminateCallFramePseudoInstr.
4708 int BytesCalleePops =
4709 (CallConv == CallingConv::Fast &&
4710 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4712 // Add a register mask operand representing the call-preserved registers.
4713 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4714 const uint32_t *Mask =
4715 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4716 assert(Mask && "Missing call preserved mask for calling convention");
4717 Ops.push_back(DAG.getRegisterMask(Mask));
4719 if (InFlag.getNode())
4720 Ops.push_back(InFlag);
4724 assert(((Callee.getOpcode() == ISD::Register &&
4725 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4726 Callee.getOpcode() == ISD::TargetExternalSymbol ||
4727 Callee.getOpcode() == ISD::TargetGlobalAddress ||
4728 isa<ConstantSDNode>(Callee)) &&
4729 "Expecting an global address, external symbol, absolute value or register");
4731 DAG.getMachineFunction().getFrameInfo().setHasTailCall();
4732 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4735 // Add a NOP immediately after the branch instruction when using the 64-bit
4736 // SVR4 ABI. At link time, if caller and callee are in a different module and
4737 // thus have a different TOC, the call will be replaced with a call to a stub
4738 // function which saves the current TOC, loads the TOC of the callee and
4739 // branches to the callee. The NOP will be replaced with a load instruction
4740 // which restores the TOC of the caller from the TOC save slot of the current
4741 // stack frame. If caller and callee belong to the same module (and have the
4742 // same TOC), the NOP will remain unchanged.
4744 MachineFunction &MF = DAG.getMachineFunction();
4745 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4747 if (CallOpc == PPCISD::BCTRL) {
4748 // This is a call through a function pointer.
4749 // Restore the caller TOC from the save area into R2.
4750 // See PrepareCall() for more information about calls through function
4751 // pointers in the 64-bit SVR4 ABI.
4752 // We are using a target-specific load with r2 hard coded, because the
4753 // result of a target-independent load would never go directly into r2,
4754 // since r2 is a reserved register (which prevents the register allocator
4755 // from allocating it), resulting in an additional register being
4756 // allocated and an unnecessary move instruction being generated.
4757 CallOpc = PPCISD::BCTRL_LOAD_TOC;
4759 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4760 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4761 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4762 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4763 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4765 // The address needs to go after the chain input but before the flag (or
4766 // any other variadic arguments).
4767 Ops.insert(std::next(Ops.begin()), AddTOC);
4768 } else if (CallOpc == PPCISD::CALL &&
4769 !resideInSameSection(MF.getFunction(), Callee, DAG.getTarget())) {
4770 // Otherwise insert NOP for non-local calls.
4771 CallOpc = PPCISD::CALL_NOP;
4775 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4776 InFlag = Chain.getValue(1);
4778 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4779 DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4782 InFlag = Chain.getValue(1);
4784 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4785 Ins, dl, DAG, InVals);
4789 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4790 SmallVectorImpl<SDValue> &InVals) const {
4791 SelectionDAG &DAG = CLI.DAG;
4793 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4794 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
4795 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
4796 SDValue Chain = CLI.Chain;
4797 SDValue Callee = CLI.Callee;
4798 bool &isTailCall = CLI.IsTailCall;
4799 CallingConv::ID CallConv = CLI.CallConv;
4800 bool isVarArg = CLI.IsVarArg;
4801 bool isPatchPoint = CLI.IsPatchPoint;
4802 ImmutableCallSite *CS = CLI.CS;
4805 if (Subtarget.useLongCalls() && !(CS && CS->isMustTailCall()))
4807 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
4809 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
4810 isVarArg, Outs, Ins, DAG);
4812 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4816 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4819 assert(isa<GlobalAddressSDNode>(Callee) &&
4820 "Callee should be an llvm::Function object.");
4822 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
4823 const unsigned Width = 80 - strlen("TCO caller: ")
4824 - strlen(", callee linkage: 0, 0");
4825 dbgs() << "TCO caller: "
4826 << left_justify(DAG.getMachineFunction().getName(), Width)
4827 << ", callee linkage: "
4828 << GV->getVisibility() << ", " << GV->getLinkage() << "\n"
4833 if (!isTailCall && CS && CS->isMustTailCall())
4834 report_fatal_error("failed to perform tail call elimination on a call "
4835 "site marked musttail");
4837 // When long calls (i.e. indirect calls) are always used, calls are always
4838 // made via function pointer. If we have a function name, first translate it
4840 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
4842 Callee = LowerGlobalAddress(Callee, DAG);
4844 if (Subtarget.isSVR4ABI()) {
4845 if (Subtarget.isPPC64())
4846 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4847 isTailCall, isPatchPoint, Outs, OutVals, Ins,
4848 dl, DAG, InVals, CS);
4850 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4851 isTailCall, isPatchPoint, Outs, OutVals, Ins,
4852 dl, DAG, InVals, CS);
4855 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4856 isTailCall, isPatchPoint, Outs, OutVals, Ins,
4857 dl, DAG, InVals, CS);
4860 SDValue PPCTargetLowering::LowerCall_32SVR4(
4861 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4862 bool isTailCall, bool isPatchPoint,
4863 const SmallVectorImpl<ISD::OutputArg> &Outs,
4864 const SmallVectorImpl<SDValue> &OutVals,
4865 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4866 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
4867 ImmutableCallSite *CS) const {
4868 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4869 // of the 32-bit SVR4 ABI stack frame layout.
4871 assert((CallConv == CallingConv::C ||
4872 CallConv == CallingConv::Fast) && "Unknown calling convention!");
4874 unsigned PtrByteSize = 4;
4876 MachineFunction &MF = DAG.getMachineFunction();
4878 // Mark this function as potentially containing a function that contains a
4879 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4880 // and restoring the callers stack pointer in this functions epilog. This is
4881 // done because by tail calling the called function might overwrite the value
4882 // in this function's (MF) stack pointer stack slot 0(SP).
4883 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4884 CallConv == CallingConv::Fast)
4885 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4887 // Count how many bytes are to be pushed on the stack, including the linkage
4888 // area, parameter list area and the part of the local variable space which
4889 // contains copies of aggregates which are passed by value.
4891 // Assign locations to all of the outgoing arguments.
4892 SmallVector<CCValAssign, 16> ArgLocs;
4893 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
4895 // Reserve space for the linkage area on the stack.
4896 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4899 CCInfo.PreAnalyzeCallOperands(Outs);
4902 // Handle fixed and variable vector arguments differently.
4903 // Fixed vector arguments go into registers as long as registers are
4904 // available. Variable vector arguments always go into memory.
4905 unsigned NumArgs = Outs.size();
4907 for (unsigned i = 0; i != NumArgs; ++i) {
4908 MVT ArgVT = Outs[i].VT;
4909 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4912 if (Outs[i].IsFixed) {
4913 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4916 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4922 errs() << "Call operand #" << i << " has unhandled type "
4923 << EVT(ArgVT).getEVTString() << "\n";
4925 llvm_unreachable(nullptr);
4929 // All arguments are treated the same.
4930 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4932 CCInfo.clearWasPPCF128();
4934 // Assign locations to all of the outgoing aggregate by value arguments.
4935 SmallVector<CCValAssign, 16> ByValArgLocs;
4936 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
4938 // Reserve stack space for the allocations in CCInfo.
4939 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4941 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4943 // Size of the linkage area, parameter list area and the part of the local
4944 // space variable where copies of aggregates which are passed by value are
4946 unsigned NumBytes = CCByValInfo.getNextStackOffset();
4948 // Calculate by how many bytes the stack has to be adjusted in case of tail
4949 // call optimization.
4950 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4952 // Adjust the stack pointer for the new arguments...
4953 // These operations are automatically eliminated by the prolog/epilog pass
4954 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4956 SDValue CallSeqStart = Chain;
4958 // Load the return address and frame pointer so it can be moved somewhere else
4961 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
4963 // Set up a copy of the stack pointer for use loading and storing any
4964 // arguments that may not fit in the registers available for argument
4966 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4968 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4969 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4970 SmallVector<SDValue, 8> MemOpChains;
4972 bool seenFloatArg = false;
4973 // Walk the register/memloc assignments, inserting copies/loads.
4974 for (unsigned i = 0, j = 0, e = ArgLocs.size();
4977 CCValAssign &VA = ArgLocs[i];
4978 SDValue Arg = OutVals[i];
4979 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4981 if (Flags.isByVal()) {
4982 // Argument is an aggregate which is passed by value, thus we need to
4983 // create a copy of it in the local variable space of the current stack
4984 // frame (which is the stack frame of the caller) and pass the address of
4985 // this copy to the callee.
4986 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4987 CCValAssign &ByValVA = ByValArgLocs[j++];
4988 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4990 // Memory reserved in the local variable space of the callers stack frame.
4991 unsigned LocMemOffset = ByValVA.getLocMemOffset();
4993 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4994 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4997 // Create a copy of the argument in the local area of the current
4999 SDValue MemcpyCall =
5000 CreateCopyOfByValArgument(Arg, PtrOff,
5001 CallSeqStart.getNode()->getOperand(0),
5004 // This must go outside the CALLSEQ_START..END.
5005 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
5006 CallSeqStart.getNode()->getOperand(1),
5008 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5009 NewCallSeqStart.getNode());
5010 Chain = CallSeqStart = NewCallSeqStart;
5012 // Pass the address of the aggregate copy on the stack either in a
5013 // physical register or in the parameter list area of the current stack
5014 // frame to the callee.
5018 if (VA.isRegLoc()) {
5019 if (Arg.getValueType() == MVT::i1)
5020 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
5022 seenFloatArg |= VA.getLocVT().isFloatingPoint();
5023 // Put argument in a physical register.
5024 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5026 // Put argument in the parameter list area of the current stack frame.
5027 assert(VA.isMemLoc());
5028 unsigned LocMemOffset = VA.getLocMemOffset();
5031 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5032 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5035 MemOpChains.push_back(
5036 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5038 // Calculate and remember argument location.
5039 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5045 if (!MemOpChains.empty())
5046 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5048 // Build a sequence of copy-to-reg nodes chained together with token chain
5049 // and flag operands which copy the outgoing args into the appropriate regs.
5051 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5052 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5053 RegsToPass[i].second, InFlag);
5054 InFlag = Chain.getValue(1);
5057 // Set CR bit 6 to true if this is a vararg call with floating args passed in
5060 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5061 SDValue Ops[] = { Chain, InFlag };
5063 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5064 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5066 InFlag = Chain.getValue(1);
5070 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5073 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5074 /* unused except on PPC64 ELFv1 */ false, DAG,
5075 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5076 NumBytes, Ins, InVals, CS);
5079 // Copy an argument into memory, being careful to do this outside the
5080 // call sequence for the call to which the argument belongs.
5081 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5082 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5083 SelectionDAG &DAG, const SDLoc &dl) const {
5084 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5085 CallSeqStart.getNode()->getOperand(0),
5087 // The MEMCPY must go outside the CALLSEQ_START..END.
5088 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
5089 CallSeqStart.getNode()->getOperand(1),
5091 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5092 NewCallSeqStart.getNode());
5093 return NewCallSeqStart;
5096 SDValue PPCTargetLowering::LowerCall_64SVR4(
5097 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5098 bool isTailCall, bool isPatchPoint,
5099 const SmallVectorImpl<ISD::OutputArg> &Outs,
5100 const SmallVectorImpl<SDValue> &OutVals,
5101 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5102 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5103 ImmutableCallSite *CS) const {
5104 bool isELFv2ABI = Subtarget.isELFv2ABI();
5105 bool isLittleEndian = Subtarget.isLittleEndian();
5106 unsigned NumOps = Outs.size();
5107 bool hasNest = false;
5108 bool IsSibCall = false;
5110 EVT PtrVT = getPointerTy(DAG.getDataLayout());
5111 unsigned PtrByteSize = 8;
5113 MachineFunction &MF = DAG.getMachineFunction();
5115 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5118 // Mark this function as potentially containing a function that contains a
5119 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5120 // and restoring the callers stack pointer in this functions epilog. This is
5121 // done because by tail calling the called function might overwrite the value
5122 // in this function's (MF) stack pointer stack slot 0(SP).
5123 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5124 CallConv == CallingConv::Fast)
5125 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5127 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5128 "fastcc not supported on varargs functions");
5130 // Count how many bytes are to be pushed on the stack, including the linkage
5131 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
5132 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5133 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5134 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5135 unsigned NumBytes = LinkageSize;
5136 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5137 unsigned &QFPR_idx = FPR_idx;
5139 static const MCPhysReg GPR[] = {
5140 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5141 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5143 static const MCPhysReg VR[] = {
5144 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5145 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5148 const unsigned NumGPRs = array_lengthof(GPR);
5149 const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5150 const unsigned NumVRs = array_lengthof(VR);
5151 const unsigned NumQFPRs = NumFPRs;
5153 // On ELFv2, we can avoid allocating the parameter area if all the arguments
5154 // can be passed to the callee in registers.
5155 // For the fast calling convention, there is another check below.
5156 // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5157 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5158 if (!HasParameterArea) {
5159 unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5160 unsigned AvailableFPRs = NumFPRs;
5161 unsigned AvailableVRs = NumVRs;
5162 unsigned NumBytesTmp = NumBytes;
5163 for (unsigned i = 0; i != NumOps; ++i) {
5164 if (Outs[i].Flags.isNest()) continue;
5165 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5166 PtrByteSize, LinkageSize, ParamAreaSize,
5167 NumBytesTmp, AvailableFPRs, AvailableVRs,
5168 Subtarget.hasQPX()))
5169 HasParameterArea = true;
5173 // When using the fast calling convention, we don't provide backing for
5174 // arguments that will be in registers.
5175 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5177 // Add up all the space actually used.
5178 for (unsigned i = 0; i != NumOps; ++i) {
5179 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5180 EVT ArgVT = Outs[i].VT;
5181 EVT OrigVT = Outs[i].ArgVT;
5186 if (CallConv == CallingConv::Fast) {
5187 if (Flags.isByVal())
5188 NumGPRsUsed += (Flags.getByValSize()+7)/8;
5190 switch (ArgVT.getSimpleVT().SimpleTy) {
5191 default: llvm_unreachable("Unexpected ValueType for argument!");
5195 if (++NumGPRsUsed <= NumGPRs)
5204 if (++NumVRsUsed <= NumVRs)
5208 // When using QPX, this is handled like a FP register, otherwise, it
5209 // is an Altivec register.
5210 if (Subtarget.hasQPX()) {
5211 if (++NumFPRsUsed <= NumFPRs)
5214 if (++NumVRsUsed <= NumVRs)
5220 case MVT::v4f64: // QPX
5221 case MVT::v4i1: // QPX
5222 if (++NumFPRsUsed <= NumFPRs)
5228 /* Respect alignment of argument on the stack. */
5230 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5231 NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5233 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5234 if (Flags.isInConsecutiveRegsLast())
5235 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5238 unsigned NumBytesActuallyUsed = NumBytes;
5240 // In the old ELFv1 ABI,
5241 // the prolog code of the callee may store up to 8 GPR argument registers to
5242 // the stack, allowing va_start to index over them in memory if its varargs.
5243 // Because we cannot tell if this is needed on the caller side, we have to
5244 // conservatively assume that it is needed. As such, make sure we have at
5245 // least enough stack space for the caller to store the 8 GPRs.
5246 // In the ELFv2 ABI, we allocate the parameter area iff a callee
5247 // really requires memory operands, e.g. a vararg function.
5248 if (HasParameterArea)
5249 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5251 NumBytes = LinkageSize;
5253 // Tail call needs the stack to be aligned.
5254 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5255 CallConv == CallingConv::Fast)
5256 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5260 // Calculate by how many bytes the stack has to be adjusted in case of tail
5261 // call optimization.
5263 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5265 // To protect arguments on the stack from being clobbered in a tail call,
5266 // force all the loads to happen before doing any other lowering.
5268 Chain = DAG.getStackArgumentTokenFactor(Chain);
5270 // Adjust the stack pointer for the new arguments...
5271 // These operations are automatically eliminated by the prolog/epilog pass
5273 Chain = DAG.getCALLSEQ_START(Chain,
5274 DAG.getIntPtrConstant(NumBytes, dl, true), dl);
5275 SDValue CallSeqStart = Chain;
5277 // Load the return address and frame pointer so it can be move somewhere else
5280 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5282 // Set up a copy of the stack pointer for use loading and storing any
5283 // arguments that may not fit in the registers available for argument
5285 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5287 // Figure out which arguments are going to go in registers, and which in
5288 // memory. Also, if this is a vararg function, floating point operations
5289 // must be stored to our stack, and loaded into integer regs as well, if
5290 // any integer regs are available for argument passing.
5291 unsigned ArgOffset = LinkageSize;
5293 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5294 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5296 SmallVector<SDValue, 8> MemOpChains;
5297 for (unsigned i = 0; i != NumOps; ++i) {
5298 SDValue Arg = OutVals[i];
5299 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5300 EVT ArgVT = Outs[i].VT;
5301 EVT OrigVT = Outs[i].ArgVT;
5303 // PtrOff will be used to store the current argument to the stack if a
5304 // register cannot be found for it.
5307 // We re-align the argument offset for each argument, except when using the
5308 // fast calling convention, when we need to make sure we do that only when
5309 // we'll actually use a stack slot.
5310 auto ComputePtrOff = [&]() {
5311 /* Respect alignment of argument on the stack. */
5313 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5314 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5316 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5318 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5321 if (CallConv != CallingConv::Fast) {
5324 /* Compute GPR index associated with argument offset. */
5325 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5326 GPR_idx = std::min(GPR_idx, NumGPRs);
5329 // Promote integers to 64-bit values.
5330 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5331 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5332 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5333 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5336 // FIXME memcpy is used way more than necessary. Correctness first.
5337 // Note: "by value" is code for passing a structure by value, not
5339 if (Flags.isByVal()) {
5340 // Note: Size includes alignment padding, so
5341 // struct x { short a; char b; }
5342 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
5343 // These are the proper values we need for right-justifying the
5344 // aggregate in a parameter register.
5345 unsigned Size = Flags.getByValSize();
5347 // An empty aggregate parameter takes up no storage and no
5352 if (CallConv == CallingConv::Fast)
5355 // All aggregates smaller than 8 bytes must be passed right-justified.
5356 if (Size==1 || Size==2 || Size==4) {
5357 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5358 if (GPR_idx != NumGPRs) {
5359 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5360 MachinePointerInfo(), VT);
5361 MemOpChains.push_back(Load.getValue(1));
5362 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5364 ArgOffset += PtrByteSize;
5369 if (GPR_idx == NumGPRs && Size < 8) {
5370 SDValue AddPtr = PtrOff;
5371 if (!isLittleEndian) {
5372 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5373 PtrOff.getValueType());
5374 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5376 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5379 ArgOffset += PtrByteSize;
5382 // Copy entire object into memory. There are cases where gcc-generated
5383 // code assumes it is there, even if it could be put entirely into
5384 // registers. (This is not what the doc says.)
5386 // FIXME: The above statement is likely due to a misunderstanding of the
5387 // documents. All arguments must be copied into the parameter area BY
5388 // THE CALLEE in the event that the callee takes the address of any
5389 // formal argument. That has not yet been implemented. However, it is
5390 // reasonable to use the stack area as a staging area for the register
5393 // Skip this for small aggregates, as we will use the same slot for a
5394 // right-justified copy, below.
5396 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5400 // When a register is available, pass a small aggregate right-justified.
5401 if (Size < 8 && GPR_idx != NumGPRs) {
5402 // The easiest way to get this right-justified in a register
5403 // is to copy the structure into the rightmost portion of a
5404 // local variable slot, then load the whole slot into the
5406 // FIXME: The memcpy seems to produce pretty awful code for
5407 // small aggregates, particularly for packed ones.
5408 // FIXME: It would be preferable to use the slot in the
5409 // parameter save area instead of a new local variable.
5410 SDValue AddPtr = PtrOff;
5411 if (!isLittleEndian) {
5412 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5413 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5415 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5419 // Load the slot into the register.
5421 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5422 MemOpChains.push_back(Load.getValue(1));
5423 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5425 // Done with this argument.
5426 ArgOffset += PtrByteSize;
5430 // For aggregates larger than PtrByteSize, copy the pieces of the
5431 // object that fit into registers from the parameter save area.
5432 for (unsigned j=0; j<Size; j+=PtrByteSize) {
5433 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5434 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5435 if (GPR_idx != NumGPRs) {
5437 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5438 MemOpChains.push_back(Load.getValue(1));
5439 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5440 ArgOffset += PtrByteSize;
5442 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5449 switch (Arg.getSimpleValueType().SimpleTy) {
5450 default: llvm_unreachable("Unexpected ValueType for argument!");
5454 if (Flags.isNest()) {
5455 // The 'nest' parameter, if any, is passed in R11.
5456 RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5461 // These can be scalar arguments or elements of an integer array type
5462 // passed directly. Clang may use those instead of "byval" aggregate
5463 // types to avoid forcing arguments to memory unnecessarily.
5464 if (GPR_idx != NumGPRs) {
5465 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5467 if (CallConv == CallingConv::Fast)
5470 assert(HasParameterArea &&
5471 "Parameter area must exist to pass an argument in memory.");
5472 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5473 true, isTailCall, false, MemOpChains,
5474 TailCallArguments, dl);
5475 if (CallConv == CallingConv::Fast)
5476 ArgOffset += PtrByteSize;
5478 if (CallConv != CallingConv::Fast)
5479 ArgOffset += PtrByteSize;
5483 // These can be scalar arguments or elements of a float array type
5484 // passed directly. The latter are used to implement ELFv2 homogenous
5485 // float aggregates.
5487 // Named arguments go into FPRs first, and once they overflow, the
5488 // remaining arguments go into GPRs and then the parameter save area.
5489 // Unnamed arguments for vararg functions always go to GPRs and
5490 // then the parameter save area. For now, put all arguments to vararg
5491 // routines always in both locations (FPR *and* GPR or stack slot).
5492 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5493 bool NeededLoad = false;
5495 // First load the argument into the next available FPR.
5496 if (FPR_idx != NumFPRs)
5497 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5499 // Next, load the argument into GPR or stack slot if needed.
5500 if (!NeedGPROrStack)
5502 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5503 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5504 // once we support fp <-> gpr moves.
5506 // In the non-vararg case, this can only ever happen in the
5507 // presence of f32 array types, since otherwise we never run
5508 // out of FPRs before running out of GPRs.
5511 // Double values are always passed in a single GPR.
5512 if (Arg.getValueType() != MVT::f32) {
5513 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5515 // Non-array float values are extended and passed in a GPR.
5516 } else if (!Flags.isInConsecutiveRegs()) {
5517 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5518 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5520 // If we have an array of floats, we collect every odd element
5521 // together with its predecessor into one GPR.
5522 } else if (ArgOffset % PtrByteSize != 0) {
5524 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5525 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5526 if (!isLittleEndian)
5528 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5530 // The final element, if even, goes into the first half of a GPR.
5531 } else if (Flags.isInConsecutiveRegsLast()) {
5532 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5533 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5534 if (!isLittleEndian)
5535 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5536 DAG.getConstant(32, dl, MVT::i32));
5538 // Non-final even elements are skipped; they will be handled
5539 // together the with subsequent argument on the next go-around.
5543 if (ArgVal.getNode())
5544 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5546 if (CallConv == CallingConv::Fast)
5549 // Single-precision floating-point values are mapped to the
5550 // second (rightmost) word of the stack doubleword.
5551 if (Arg.getValueType() == MVT::f32 &&
5552 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5553 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5554 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5557 assert(HasParameterArea &&
5558 "Parameter area must exist to pass an argument in memory.");
5559 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5560 true, isTailCall, false, MemOpChains,
5561 TailCallArguments, dl);
5565 // When passing an array of floats, the array occupies consecutive
5566 // space in the argument area; only round up to the next doubleword
5567 // at the end of the array. Otherwise, each float takes 8 bytes.
5568 if (CallConv != CallingConv::Fast || NeededLoad) {
5569 ArgOffset += (Arg.getValueType() == MVT::f32 &&
5570 Flags.isInConsecutiveRegs()) ? 4 : 8;
5571 if (Flags.isInConsecutiveRegsLast())
5572 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5583 if (!Subtarget.hasQPX()) {
5584 // These can be scalar arguments or elements of a vector array type
5585 // passed directly. The latter are used to implement ELFv2 homogenous
5586 // vector aggregates.
5588 // For a varargs call, named arguments go into VRs or on the stack as
5589 // usual; unnamed arguments always go to the stack or the corresponding
5590 // GPRs when within range. For now, we always put the value in both
5591 // locations (or even all three).
5593 assert(HasParameterArea &&
5594 "Parameter area must exist if we have a varargs call.");
5595 // We could elide this store in the case where the object fits
5596 // entirely in R registers. Maybe later.
5598 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5599 MemOpChains.push_back(Store);
5600 if (VR_idx != NumVRs) {
5602 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5603 MemOpChains.push_back(Load.getValue(1));
5604 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5607 for (unsigned i=0; i<16; i+=PtrByteSize) {
5608 if (GPR_idx == NumGPRs)
5610 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5611 DAG.getConstant(i, dl, PtrVT));
5613 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5614 MemOpChains.push_back(Load.getValue(1));
5615 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5620 // Non-varargs Altivec params go into VRs or on the stack.
5621 if (VR_idx != NumVRs) {
5622 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5624 if (CallConv == CallingConv::Fast)
5627 assert(HasParameterArea &&
5628 "Parameter area must exist to pass an argument in memory.");
5629 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5630 true, isTailCall, true, MemOpChains,
5631 TailCallArguments, dl);
5632 if (CallConv == CallingConv::Fast)
5636 if (CallConv != CallingConv::Fast)
5641 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5642 "Invalid QPX parameter type");
5647 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5649 assert(HasParameterArea &&
5650 "Parameter area must exist if we have a varargs call.");
5651 // We could elide this store in the case where the object fits
5652 // entirely in R registers. Maybe later.
5654 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5655 MemOpChains.push_back(Store);
5656 if (QFPR_idx != NumQFPRs) {
5657 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
5658 PtrOff, MachinePointerInfo());
5659 MemOpChains.push_back(Load.getValue(1));
5660 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5662 ArgOffset += (IsF32 ? 16 : 32);
5663 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5664 if (GPR_idx == NumGPRs)
5666 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5667 DAG.getConstant(i, dl, PtrVT));
5669 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5670 MemOpChains.push_back(Load.getValue(1));
5671 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5676 // Non-varargs QPX params go into registers or on the stack.
5677 if (QFPR_idx != NumQFPRs) {
5678 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5680 if (CallConv == CallingConv::Fast)
5683 assert(HasParameterArea &&
5684 "Parameter area must exist to pass an argument in memory.");
5685 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5686 true, isTailCall, true, MemOpChains,
5687 TailCallArguments, dl);
5688 if (CallConv == CallingConv::Fast)
5689 ArgOffset += (IsF32 ? 16 : 32);
5692 if (CallConv != CallingConv::Fast)
5693 ArgOffset += (IsF32 ? 16 : 32);
5699 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
5700 "mismatch in size of parameter area");
5701 (void)NumBytesActuallyUsed;
5703 if (!MemOpChains.empty())
5704 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5706 // Check if this is an indirect call (MTCTR/BCTRL).
5707 // See PrepareCall() for more information about calls through function
5708 // pointers in the 64-bit SVR4 ABI.
5709 if (!isTailCall && !isPatchPoint &&
5710 !isFunctionGlobalAddress(Callee) &&
5711 !isa<ExternalSymbolSDNode>(Callee)) {
5712 // Load r2 into a virtual register and store it to the TOC save area.
5713 setUsesTOCBasePtr(DAG);
5714 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5715 // TOC save area offset.
5716 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5717 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5718 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5719 Chain = DAG.getStore(
5720 Val.getValue(1), dl, Val, AddPtr,
5721 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
5722 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5723 // This does not mean the MTCTR instruction must use R12; it's easier
5724 // to model this as an extra parameter, so do that.
5725 if (isELFv2ABI && !isPatchPoint)
5726 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5729 // Build a sequence of copy-to-reg nodes chained together with token chain
5730 // and flag operands which copy the outgoing args into the appropriate regs.
5732 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5733 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5734 RegsToPass[i].second, InFlag);
5735 InFlag = Chain.getValue(1);
5738 if (isTailCall && !IsSibCall)
5739 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5742 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
5743 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
5744 SPDiff, NumBytes, Ins, InVals, CS);
5747 SDValue PPCTargetLowering::LowerCall_Darwin(
5748 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5749 bool isTailCall, bool isPatchPoint,
5750 const SmallVectorImpl<ISD::OutputArg> &Outs,
5751 const SmallVectorImpl<SDValue> &OutVals,
5752 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5753 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5754 ImmutableCallSite *CS) const {
5755 unsigned NumOps = Outs.size();
5757 EVT PtrVT = getPointerTy(DAG.getDataLayout());
5758 bool isPPC64 = PtrVT == MVT::i64;
5759 unsigned PtrByteSize = isPPC64 ? 8 : 4;
5761 MachineFunction &MF = DAG.getMachineFunction();
5763 // Mark this function as potentially containing a function that contains a
5764 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5765 // and restoring the callers stack pointer in this functions epilog. This is
5766 // done because by tail calling the called function might overwrite the value
5767 // in this function's (MF) stack pointer stack slot 0(SP).
5768 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5769 CallConv == CallingConv::Fast)
5770 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5772 // Count how many bytes are to be pushed on the stack, including the linkage
5773 // area, and parameter passing area. We start with 24/48 bytes, which is
5774 // prereserved space for [SP][CR][LR][3 x unused].
5775 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5776 unsigned NumBytes = LinkageSize;
5778 // Add up all the space actually used.
5779 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5780 // they all go in registers, but we must reserve stack space for them for
5781 // possible use by the caller. In varargs or 64-bit calls, parameters are
5782 // assigned stack space in order, with padding so Altivec parameters are
5784 unsigned nAltivecParamsAtEnd = 0;
5785 for (unsigned i = 0; i != NumOps; ++i) {
5786 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5787 EVT ArgVT = Outs[i].VT;
5788 // Varargs Altivec parameters are padded to a 16 byte boundary.
5789 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5790 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5791 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5792 if (!isVarArg && !isPPC64) {
5793 // Non-varargs Altivec parameters go after all the non-Altivec
5794 // parameters; handle those later so we know how much padding we need.
5795 nAltivecParamsAtEnd++;
5798 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5799 NumBytes = ((NumBytes+15)/16)*16;
5801 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5804 // Allow for Altivec parameters at the end, if needed.
5805 if (nAltivecParamsAtEnd) {
5806 NumBytes = ((NumBytes+15)/16)*16;
5807 NumBytes += 16*nAltivecParamsAtEnd;
5810 // The prolog code of the callee may store up to 8 GPR argument registers to
5811 // the stack, allowing va_start to index over them in memory if its varargs.
5812 // Because we cannot tell if this is needed on the caller side, we have to
5813 // conservatively assume that it is needed. As such, make sure we have at
5814 // least enough stack space for the caller to store the 8 GPRs.
5815 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5817 // Tail call needs the stack to be aligned.
5818 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5819 CallConv == CallingConv::Fast)
5820 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5822 // Calculate by how many bytes the stack has to be adjusted in case of tail
5823 // call optimization.
5824 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5826 // To protect arguments on the stack from being clobbered in a tail call,
5827 // force all the loads to happen before doing any other lowering.
5829 Chain = DAG.getStackArgumentTokenFactor(Chain);
5831 // Adjust the stack pointer for the new arguments...
5832 // These operations are automatically eliminated by the prolog/epilog pass
5833 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5835 SDValue CallSeqStart = Chain;
5837 // Load the return address and frame pointer so it can be move somewhere else
5840 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5842 // Set up a copy of the stack pointer for use loading and storing any
5843 // arguments that may not fit in the registers available for argument
5847 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5849 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5851 // Figure out which arguments are going to go in registers, and which in
5852 // memory. Also, if this is a vararg function, floating point operations
5853 // must be stored to our stack, and loaded into integer regs as well, if
5854 // any integer regs are available for argument passing.
5855 unsigned ArgOffset = LinkageSize;
5856 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5858 static const MCPhysReg GPR_32[] = { // 32-bit registers.
5859 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5860 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5862 static const MCPhysReg GPR_64[] = { // 64-bit registers.
5863 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5864 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5866 static const MCPhysReg VR[] = {
5867 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5868 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5870 const unsigned NumGPRs = array_lengthof(GPR_32);
5871 const unsigned NumFPRs = 13;
5872 const unsigned NumVRs = array_lengthof(VR);
5874 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5876 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5877 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5879 SmallVector<SDValue, 8> MemOpChains;
5880 for (unsigned i = 0; i != NumOps; ++i) {
5881 SDValue Arg = OutVals[i];
5882 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5884 // PtrOff will be used to store the current argument to the stack if a
5885 // register cannot be found for it.
5888 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5890 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5892 // On PPC64, promote integers to 64-bit values.
5893 if (isPPC64 && Arg.getValueType() == MVT::i32) {
5894 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5895 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5896 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5899 // FIXME memcpy is used way more than necessary. Correctness first.
5900 // Note: "by value" is code for passing a structure by value, not
5902 if (Flags.isByVal()) {
5903 unsigned Size = Flags.getByValSize();
5904 // Very small objects are passed right-justified. Everything else is
5905 // passed left-justified.
5906 if (Size==1 || Size==2) {
5907 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5908 if (GPR_idx != NumGPRs) {
5909 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5910 MachinePointerInfo(), VT);
5911 MemOpChains.push_back(Load.getValue(1));
5912 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5914 ArgOffset += PtrByteSize;
5916 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5917 PtrOff.getValueType());
5918 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5919 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5922 ArgOffset += PtrByteSize;
5926 // Copy entire object into memory. There are cases where gcc-generated
5927 // code assumes it is there, even if it could be put entirely into
5928 // registers. (This is not what the doc says.)
5929 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5933 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5934 // copy the pieces of the object that fit into registers from the
5935 // parameter save area.
5936 for (unsigned j=0; j<Size; j+=PtrByteSize) {
5937 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5938 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5939 if (GPR_idx != NumGPRs) {
5941 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5942 MemOpChains.push_back(Load.getValue(1));
5943 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5944 ArgOffset += PtrByteSize;
5946 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5953 switch (Arg.getSimpleValueType().SimpleTy) {
5954 default: llvm_unreachable("Unexpected ValueType for argument!");
5958 if (GPR_idx != NumGPRs) {
5959 if (Arg.getValueType() == MVT::i1)
5960 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5962 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5964 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5965 isPPC64, isTailCall, false, MemOpChains,
5966 TailCallArguments, dl);
5968 ArgOffset += PtrByteSize;
5972 if (FPR_idx != NumFPRs) {
5973 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5977 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5978 MemOpChains.push_back(Store);
5980 // Float varargs are always shadowed in available integer registers
5981 if (GPR_idx != NumGPRs) {
5983 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
5984 MemOpChains.push_back(Load.getValue(1));
5985 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5987 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5988 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5989 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5991 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
5992 MemOpChains.push_back(Load.getValue(1));
5993 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5996 // If we have any FPRs remaining, we may also have GPRs remaining.
5997 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5999 if (GPR_idx != NumGPRs)
6001 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6002 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
6006 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6007 isPPC64, isTailCall, false, MemOpChains,
6008 TailCallArguments, dl);
6012 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6019 // These go aligned on the stack, or in the corresponding R registers
6020 // when within range. The Darwin PPC ABI doc claims they also go in
6021 // V registers; in fact gcc does this only for arguments that are
6022 // prototyped, not for those that match the ... We do it for all
6023 // arguments, seems to work.
6024 while (ArgOffset % 16 !=0) {
6025 ArgOffset += PtrByteSize;
6026 if (GPR_idx != NumGPRs)
6029 // We could elide this store in the case where the object fits
6030 // entirely in R registers. Maybe later.
6031 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6032 DAG.getConstant(ArgOffset, dl, PtrVT));
6034 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6035 MemOpChains.push_back(Store);
6036 if (VR_idx != NumVRs) {
6038 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6039 MemOpChains.push_back(Load.getValue(1));
6040 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6043 for (unsigned i=0; i<16; i+=PtrByteSize) {
6044 if (GPR_idx == NumGPRs)
6046 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6047 DAG.getConstant(i, dl, PtrVT));
6049 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6050 MemOpChains.push_back(Load.getValue(1));
6051 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6056 // Non-varargs Altivec params generally go in registers, but have
6057 // stack space allocated at the end.
6058 if (VR_idx != NumVRs) {
6059 // Doesn't have GPR space allocated.
6060 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6061 } else if (nAltivecParamsAtEnd==0) {
6062 // We are emitting Altivec params in order.
6063 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6064 isPPC64, isTailCall, true, MemOpChains,
6065 TailCallArguments, dl);
6071 // If all Altivec parameters fit in registers, as they usually do,
6072 // they get stack space following the non-Altivec parameters. We
6073 // don't track this here because nobody below needs it.
6074 // If there are more Altivec parameters than fit in registers emit
6076 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6078 // Offset is aligned; skip 1st 12 params which go in V registers.
6079 ArgOffset = ((ArgOffset+15)/16)*16;
6081 for (unsigned i = 0; i != NumOps; ++i) {
6082 SDValue Arg = OutVals[i];
6083 EVT ArgType = Outs[i].VT;
6084 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6085 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6088 // We are emitting Altivec params in order.
6089 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6090 isPPC64, isTailCall, true, MemOpChains,
6091 TailCallArguments, dl);
6098 if (!MemOpChains.empty())
6099 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6101 // On Darwin, R12 must contain the address of an indirect callee. This does
6102 // not mean the MTCTR instruction must use R12; it's easier to model this as
6103 // an extra parameter, so do that.
6105 !isFunctionGlobalAddress(Callee) &&
6106 !isa<ExternalSymbolSDNode>(Callee) &&
6107 !isBLACompatibleAddress(Callee, DAG))
6108 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6109 PPC::R12), Callee));
6111 // Build a sequence of copy-to-reg nodes chained together with token chain
6112 // and flag operands which copy the outgoing args into the appropriate regs.
6114 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6115 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6116 RegsToPass[i].second, InFlag);
6117 InFlag = Chain.getValue(1);
6121 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6124 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6125 /* unused except on PPC64 ELFv1 */ false, DAG,
6126 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6127 NumBytes, Ins, InVals, CS);
6131 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6132 MachineFunction &MF, bool isVarArg,
6133 const SmallVectorImpl<ISD::OutputArg> &Outs,
6134 LLVMContext &Context) const {
6135 SmallVector<CCValAssign, 16> RVLocs;
6136 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6137 return CCInfo.CheckReturn(Outs, RetCC_PPC);
6141 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6143 const SmallVectorImpl<ISD::OutputArg> &Outs,
6144 const SmallVectorImpl<SDValue> &OutVals,
6145 const SDLoc &dl, SelectionDAG &DAG) const {
6146 SmallVector<CCValAssign, 16> RVLocs;
6147 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6149 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
6152 SmallVector<SDValue, 4> RetOps(1, Chain);
6154 // Copy the result values into the output registers.
6155 for (unsigned i = 0; i != RVLocs.size(); ++i) {
6156 CCValAssign &VA = RVLocs[i];
6157 assert(VA.isRegLoc() && "Can only return in registers!");
6159 SDValue Arg = OutVals[i];
6161 switch (VA.getLocInfo()) {
6162 default: llvm_unreachable("Unknown loc info!");
6163 case CCValAssign::Full: break;
6164 case CCValAssign::AExt:
6165 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6167 case CCValAssign::ZExt:
6168 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6170 case CCValAssign::SExt:
6171 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6175 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6176 Flag = Chain.getValue(1);
6177 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6180 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6181 const MCPhysReg *I =
6182 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6186 if (PPC::G8RCRegClass.contains(*I))
6187 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6188 else if (PPC::F8RCRegClass.contains(*I))
6189 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6190 else if (PPC::CRRCRegClass.contains(*I))
6191 RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6192 else if (PPC::VRRCRegClass.contains(*I))
6193 RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6195 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6199 RetOps[0] = Chain; // Update chain.
6201 // Add the flag if we have it.
6203 RetOps.push_back(Flag);
6205 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6209 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6210 SelectionDAG &DAG) const {
6213 // Get the corect type for integers.
6214 EVT IntVT = Op.getValueType();
6217 SDValue Chain = Op.getOperand(0);
6218 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6219 // Build a DYNAREAOFFSET node.
6220 SDValue Ops[2] = {Chain, FPSIdx};
6221 SDVTList VTs = DAG.getVTList(IntVT);
6222 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6225 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6226 SelectionDAG &DAG) const {
6227 // When we pop the dynamic allocation we need to restore the SP link.
6230 // Get the corect type for pointers.
6231 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6233 // Construct the stack pointer operand.
6234 bool isPPC64 = Subtarget.isPPC64();
6235 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6236 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6238 // Get the operands for the STACKRESTORE.
6239 SDValue Chain = Op.getOperand(0);
6240 SDValue SaveSP = Op.getOperand(1);
6242 // Load the old link SP.
6243 SDValue LoadLinkSP =
6244 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6246 // Restore the stack pointer.
6247 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6249 // Store the old link SP.
6250 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6253 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6254 MachineFunction &MF = DAG.getMachineFunction();
6255 bool isPPC64 = Subtarget.isPPC64();
6256 EVT PtrVT = getPointerTy(MF.getDataLayout());
6258 // Get current frame pointer save index. The users of this index will be
6259 // primarily DYNALLOC instructions.
6260 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6261 int RASI = FI->getReturnAddrSaveIndex();
6263 // If the frame pointer save index hasn't been defined yet.
6265 // Find out what the fix offset of the frame pointer save area.
6266 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6267 // Allocate the frame index for frame pointer save area.
6268 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6270 FI->setReturnAddrSaveIndex(RASI);
6272 return DAG.getFrameIndex(RASI, PtrVT);
6276 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6277 MachineFunction &MF = DAG.getMachineFunction();
6278 bool isPPC64 = Subtarget.isPPC64();
6279 EVT PtrVT = getPointerTy(MF.getDataLayout());
6281 // Get current frame pointer save index. The users of this index will be
6282 // primarily DYNALLOC instructions.
6283 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6284 int FPSI = FI->getFramePointerSaveIndex();
6286 // If the frame pointer save index hasn't been defined yet.
6288 // Find out what the fix offset of the frame pointer save area.
6289 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6290 // Allocate the frame index for frame pointer save area.
6291 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6293 FI->setFramePointerSaveIndex(FPSI);
6295 return DAG.getFrameIndex(FPSI, PtrVT);
6298 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6299 SelectionDAG &DAG) const {
6301 SDValue Chain = Op.getOperand(0);
6302 SDValue Size = Op.getOperand(1);
6305 // Get the corect type for pointers.
6306 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6308 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6309 DAG.getConstant(0, dl, PtrVT), Size);
6310 // Construct a node for the frame pointer save index.
6311 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6312 // Build a DYNALLOC node.
6313 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6314 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6315 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6318 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6319 SelectionDAG &DAG) const {
6320 MachineFunction &MF = DAG.getMachineFunction();
6322 bool isPPC64 = Subtarget.isPPC64();
6323 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6325 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6326 return DAG.getFrameIndex(FI, PtrVT);
6329 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6330 SelectionDAG &DAG) const {
6332 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6333 DAG.getVTList(MVT::i32, MVT::Other),
6334 Op.getOperand(0), Op.getOperand(1));
6337 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6338 SelectionDAG &DAG) const {
6340 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6341 Op.getOperand(0), Op.getOperand(1));
6344 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6345 if (Op.getValueType().isVector())
6346 return LowerVectorLoad(Op, DAG);
6348 assert(Op.getValueType() == MVT::i1 &&
6349 "Custom lowering only for i1 loads");
6351 // First, load 8 bits into 32 bits, then truncate to 1 bit.
6354 LoadSDNode *LD = cast<LoadSDNode>(Op);
6356 SDValue Chain = LD->getChain();
6357 SDValue BasePtr = LD->getBasePtr();
6358 MachineMemOperand *MMO = LD->getMemOperand();
6361 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6362 BasePtr, MVT::i8, MMO);
6363 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6365 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6366 return DAG.getMergeValues(Ops, dl);
6369 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6370 if (Op.getOperand(1).getValueType().isVector())
6371 return LowerVectorStore(Op, DAG);
6373 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6374 "Custom lowering only for i1 stores");
6376 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6379 StoreSDNode *ST = cast<StoreSDNode>(Op);
6381 SDValue Chain = ST->getChain();
6382 SDValue BasePtr = ST->getBasePtr();
6383 SDValue Value = ST->getValue();
6384 MachineMemOperand *MMO = ST->getMemOperand();
6386 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6388 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6391 // FIXME: Remove this once the ANDI glue bug is fixed:
6392 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6393 assert(Op.getValueType() == MVT::i1 &&
6394 "Custom lowering only for i1 results");
6397 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6401 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6403 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6404 // Not FP? Not a fsel.
6405 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6406 !Op.getOperand(2).getValueType().isFloatingPoint())
6409 // We might be able to do better than this under some circumstances, but in
6410 // general, fsel-based lowering of select is a finite-math-only optimization.
6411 // For more information, see section F.3 of the 2.06 ISA specification.
6412 if (!DAG.getTarget().Options.NoInfsFPMath ||
6413 !DAG.getTarget().Options.NoNaNsFPMath)
6415 // TODO: Propagate flags from the select rather than global settings.
6417 Flags.setNoInfs(true);
6418 Flags.setNoNaNs(true);
6420 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6422 EVT ResVT = Op.getValueType();
6423 EVT CmpVT = Op.getOperand(0).getValueType();
6424 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6425 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
6428 // If the RHS of the comparison is a 0.0, we don't need to do the
6429 // subtraction at all.
6431 if (isFloatingPointZero(RHS))
6433 default: break; // SETUO etc aren't handled by fsel.
6437 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
6438 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6439 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6440 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
6441 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6442 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6443 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6446 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
6449 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
6450 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6451 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6454 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
6457 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
6458 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6459 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6460 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6465 default: break; // SETUO etc aren't handled by fsel.
6469 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6470 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6471 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6472 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6473 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
6474 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6475 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6476 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6479 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6480 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6481 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6482 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6485 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6486 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6487 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6488 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6491 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6492 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6493 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6494 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6497 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6498 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6499 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6500 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6505 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6507 const SDLoc &dl) const {
6508 assert(Op.getOperand(0).getValueType().isFloatingPoint());
6509 SDValue Src = Op.getOperand(0);
6510 if (Src.getValueType() == MVT::f32)
6511 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6514 switch (Op.getSimpleValueType().SimpleTy) {
6515 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6518 Op.getOpcode() == ISD::FP_TO_SINT
6520 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6524 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6525 "i64 FP_TO_UINT is supported only with FPCVT");
6526 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6532 // Convert the FP value to an int value through memory.
6533 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6534 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6535 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6536 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6537 MachinePointerInfo MPI =
6538 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6540 // Emit a store to the stack slot.
6543 MachineFunction &MF = DAG.getMachineFunction();
6544 MachineMemOperand *MMO =
6545 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6546 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6547 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6548 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6550 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
6552 // Result is a load from the stack slot. If loading 4 bytes, make sure to
6553 // add in a bias on big endian.
6554 if (Op.getValueType() == MVT::i32 && !i32Stack) {
6555 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6556 DAG.getConstant(4, dl, FIPtr.getValueType()));
6557 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6565 /// \brief Custom lowers floating point to integer conversions to use
6566 /// the direct move instructions available in ISA 2.07 to avoid the
6567 /// need for load/store combinations.
6568 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6570 const SDLoc &dl) const {
6571 assert(Op.getOperand(0).getValueType().isFloatingPoint());
6572 SDValue Src = Op.getOperand(0);
6574 if (Src.getValueType() == MVT::f32)
6575 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6578 switch (Op.getSimpleValueType().SimpleTy) {
6579 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6582 Op.getOpcode() == ISD::FP_TO_SINT
6584 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6586 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6589 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6590 "i64 FP_TO_UINT is supported only with FPCVT");
6591 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6594 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6600 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6601 const SDLoc &dl) const {
6602 if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6603 return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6606 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6608 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6609 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6612 // We're trying to insert a regular store, S, and then a load, L. If the
6613 // incoming value, O, is a load, we might just be able to have our load use the
6614 // address used by O. However, we don't know if anything else will store to
6615 // that address before we can load from it. To prevent this situation, we need
6616 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6617 // the same chain operand as O, we create a token factor from the chain results
6618 // of O and L, and we replace all uses of O's chain result with that token
6619 // factor (see spliceIntoChain below for this last part).
6620 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6623 ISD::LoadExtType ET) const {
6625 if (ET == ISD::NON_EXTLOAD &&
6626 (Op.getOpcode() == ISD::FP_TO_UINT ||
6627 Op.getOpcode() == ISD::FP_TO_SINT) &&
6628 isOperationLegalOrCustom(Op.getOpcode(),
6629 Op.getOperand(0).getValueType())) {
6631 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6635 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6636 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6637 LD->isNonTemporal())
6639 if (LD->getMemoryVT() != MemVT)
6642 RLI.Ptr = LD->getBasePtr();
6643 if (LD->isIndexed() && !LD->getOffset().isUndef()) {
6644 assert(LD->getAddressingMode() == ISD::PRE_INC &&
6645 "Non-pre-inc AM on PPC?");
6646 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6650 RLI.Chain = LD->getChain();
6651 RLI.MPI = LD->getPointerInfo();
6652 RLI.IsDereferenceable = LD->isDereferenceable();
6653 RLI.IsInvariant = LD->isInvariant();
6654 RLI.Alignment = LD->getAlignment();
6655 RLI.AAInfo = LD->getAAInfo();
6656 RLI.Ranges = LD->getRanges();
6658 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6662 // Given the head of the old chain, ResChain, insert a token factor containing
6663 // it and NewResChain, and make users of ResChain now be users of that token
6665 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6666 SDValue NewResChain,
6667 SelectionDAG &DAG) const {
6671 SDLoc dl(NewResChain);
6673 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6674 NewResChain, DAG.getUNDEF(MVT::Other));
6675 assert(TF.getNode() != NewResChain.getNode() &&
6676 "A new TF really is required here");
6678 DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6679 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6682 /// \brief Analyze profitability of direct move
6683 /// prefer float load to int load plus direct move
6684 /// when there is no integer use of int load
6685 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
6686 SDNode *Origin = Op.getOperand(0).getNode();
6687 if (Origin->getOpcode() != ISD::LOAD)
6690 // If there is no LXSIBZX/LXSIHZX, like Power8,
6691 // prefer direct move if the memory size is 1 or 2 bytes.
6692 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
6693 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
6696 for (SDNode::use_iterator UI = Origin->use_begin(),
6697 UE = Origin->use_end();
6700 // Only look at the users of the loaded value.
6701 if (UI.getUse().get().getResNo() != 0)
6704 if (UI->getOpcode() != ISD::SINT_TO_FP &&
6705 UI->getOpcode() != ISD::UINT_TO_FP)
6712 /// \brief Custom lowers integer to floating point conversions to use
6713 /// the direct move instructions available in ISA 2.07 to avoid the
6714 /// need for load/store combinations.
6715 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6717 const SDLoc &dl) const {
6718 assert((Op.getValueType() == MVT::f32 ||
6719 Op.getValueType() == MVT::f64) &&
6720 "Invalid floating point type as target of conversion");
6721 assert(Subtarget.hasFPCVT() &&
6722 "Int to FP conversions with direct moves require FPCVT");
6724 SDValue Src = Op.getOperand(0);
6725 bool SinglePrec = Op.getValueType() == MVT::f32;
6726 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6727 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6728 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6729 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6732 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6734 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6737 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6738 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6744 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6745 SelectionDAG &DAG) const {
6748 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6749 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6752 SDValue Value = Op.getOperand(0);
6753 // The values are now known to be -1 (false) or 1 (true). To convert this
6754 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6755 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6756 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6758 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
6760 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6762 if (Op.getValueType() != MVT::v4f64)
6763 Value = DAG.getNode(ISD::FP_ROUND, dl,
6764 Op.getValueType(), Value,
6765 DAG.getIntPtrConstant(1, dl));
6769 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6770 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6773 if (Op.getOperand(0).getValueType() == MVT::i1)
6774 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6775 DAG.getConstantFP(1.0, dl, Op.getValueType()),
6776 DAG.getConstantFP(0.0, dl, Op.getValueType()));
6778 // If we have direct moves, we can do all the conversion, skip the store/load
6779 // however, without FPCVT we can't do most conversions.
6780 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
6781 Subtarget.isPPC64() && Subtarget.hasFPCVT())
6782 return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6784 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6785 "UINT_TO_FP is supported only with FPCVT");
6787 // If we have FCFIDS, then use it when converting to single-precision.
6788 // Otherwise, convert to double-precision and then round.
6789 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6790 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6792 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6794 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6798 if (Op.getOperand(0).getValueType() == MVT::i64) {
6799 SDValue SINT = Op.getOperand(0);
6800 // When converting to single-precision, we actually need to convert
6801 // to double-precision first and then round to single-precision.
6802 // To avoid double-rounding effects during that operation, we have
6803 // to prepare the input operand. Bits that might be truncated when
6804 // converting to double-precision are replaced by a bit that won't
6805 // be lost at this stage, but is below the single-precision rounding
6808 // However, if -enable-unsafe-fp-math is in effect, accept double
6809 // rounding to avoid the extra overhead.
6810 if (Op.getValueType() == MVT::f32 &&
6811 !Subtarget.hasFPCVT() &&
6812 !DAG.getTarget().Options.UnsafeFPMath) {
6814 // Twiddle input to make sure the low 11 bits are zero. (If this
6815 // is the case, we are guaranteed the value will fit into the 53 bit
6816 // mantissa of an IEEE double-precision value without rounding.)
6817 // If any of those low 11 bits were not zero originally, make sure
6818 // bit 12 (value 2048) is set instead, so that the final rounding
6819 // to single-precision gets the correct result.
6820 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6821 SINT, DAG.getConstant(2047, dl, MVT::i64));
6822 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6823 Round, DAG.getConstant(2047, dl, MVT::i64));
6824 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6825 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6826 Round, DAG.getConstant(-2048, dl, MVT::i64));
6828 // However, we cannot use that value unconditionally: if the magnitude
6829 // of the input value is small, the bit-twiddling we did above might
6830 // end up visibly changing the output. Fortunately, in that case, we
6831 // don't need to twiddle bits since the original input will convert
6832 // exactly to double-precision floating-point already. Therefore,
6833 // construct a conditional to use the original value if the top 11
6834 // bits are all sign-bit copies, and use the rounded value computed
6836 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6837 SINT, DAG.getConstant(53, dl, MVT::i32));
6838 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6839 Cond, DAG.getConstant(1, dl, MVT::i64));
6840 Cond = DAG.getSetCC(dl, MVT::i32,
6841 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6843 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6849 MachineFunction &MF = DAG.getMachineFunction();
6850 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6851 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6852 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6853 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6854 } else if (Subtarget.hasLFIWAX() &&
6855 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6856 MachineMemOperand *MMO =
6857 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6858 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6859 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6860 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6861 DAG.getVTList(MVT::f64, MVT::Other),
6862 Ops, MVT::i32, MMO);
6863 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6864 } else if (Subtarget.hasFPCVT() &&
6865 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6866 MachineMemOperand *MMO =
6867 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6868 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6869 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6870 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6871 DAG.getVTList(MVT::f64, MVT::Other),
6872 Ops, MVT::i32, MMO);
6873 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6874 } else if (((Subtarget.hasLFIWAX() &&
6875 SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6876 (Subtarget.hasFPCVT() &&
6877 SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6878 SINT.getOperand(0).getValueType() == MVT::i32) {
6879 MachineFrameInfo &MFI = MF.getFrameInfo();
6880 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6882 int FrameIdx = MFI.CreateStackObject(4, 4, false);
6883 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6886 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6887 MachinePointerInfo::getFixedStack(
6888 DAG.getMachineFunction(), FrameIdx));
6890 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6891 "Expected an i32 store");
6896 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6899 MachineMemOperand *MMO =
6900 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6901 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6902 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6903 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6904 PPCISD::LFIWZX : PPCISD::LFIWAX,
6905 dl, DAG.getVTList(MVT::f64, MVT::Other),
6906 Ops, MVT::i32, MMO);
6908 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6910 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6912 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6913 FP = DAG.getNode(ISD::FP_ROUND, dl,
6914 MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6918 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6919 "Unhandled INT_TO_FP type in custom expander!");
6920 // Since we only generate this in 64-bit mode, we can take advantage of
6921 // 64-bit registers. In particular, sign extend the input value into the
6922 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6923 // then lfd it and fcfid it.
6924 MachineFunction &MF = DAG.getMachineFunction();
6925 MachineFrameInfo &MFI = MF.getFrameInfo();
6926 EVT PtrVT = getPointerTy(MF.getDataLayout());
6929 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6932 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6934 int FrameIdx = MFI.CreateStackObject(4, 4, false);
6935 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6938 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6939 MachinePointerInfo::getFixedStack(
6940 DAG.getMachineFunction(), FrameIdx));
6942 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6943 "Expected an i32 store");
6948 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6952 MachineMemOperand *MMO =
6953 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6954 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6955 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6956 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6957 PPCISD::LFIWZX : PPCISD::LFIWAX,
6958 dl, DAG.getVTList(MVT::f64, MVT::Other),
6959 Ops, MVT::i32, MMO);
6961 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6963 assert(Subtarget.isPPC64() &&
6964 "i32->FP without LFIWAX supported only on PPC64");
6966 int FrameIdx = MFI.CreateStackObject(8, 8, false);
6967 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6969 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6972 // STD the extended value into the stack slot.
6973 SDValue Store = DAG.getStore(
6974 DAG.getEntryNode(), dl, Ext64, FIdx,
6975 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6977 // Load the value as a double.
6979 MVT::f64, dl, Store, FIdx,
6980 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6983 // FCFID it and return it.
6984 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6985 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6986 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
6987 DAG.getIntPtrConstant(0, dl));
6991 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6992 SelectionDAG &DAG) const {
6995 The rounding mode is in bits 30:31 of FPSR, and has the following
7002 FLT_ROUNDS, on the other hand, expects the following:
7009 To perform the conversion, we do:
7010 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
7013 MachineFunction &MF = DAG.getMachineFunction();
7014 EVT VT = Op.getValueType();
7015 EVT PtrVT = getPointerTy(MF.getDataLayout());
7017 // Save FP Control Word to register
7019 MVT::f64, // return register
7020 MVT::Glue // unused in this context
7022 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
7024 // Save FP register to stack slot
7025 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
7026 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
7027 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
7028 MachinePointerInfo());
7030 // Load FP Control Word from low 32 bits of stack slot.
7031 SDValue Four = DAG.getConstant(4, dl, PtrVT);
7032 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
7033 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
7035 // Transform as necessary
7037 DAG.getNode(ISD::AND, dl, MVT::i32,
7038 CWD, DAG.getConstant(3, dl, MVT::i32));
7040 DAG.getNode(ISD::SRL, dl, MVT::i32,
7041 DAG.getNode(ISD::AND, dl, MVT::i32,
7042 DAG.getNode(ISD::XOR, dl, MVT::i32,
7043 CWD, DAG.getConstant(3, dl, MVT::i32)),
7044 DAG.getConstant(3, dl, MVT::i32)),
7045 DAG.getConstant(1, dl, MVT::i32));
7048 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
7050 return DAG.getNode((VT.getSizeInBits() < 16 ?
7051 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7054 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7055 EVT VT = Op.getValueType();
7056 unsigned BitWidth = VT.getSizeInBits();
7058 assert(Op.getNumOperands() == 3 &&
7059 VT == Op.getOperand(1).getValueType() &&
7062 // Expand into a bunch of logical ops. Note that these ops
7063 // depend on the PPC behavior for oversized shift amounts.
7064 SDValue Lo = Op.getOperand(0);
7065 SDValue Hi = Op.getOperand(1);
7066 SDValue Amt = Op.getOperand(2);
7067 EVT AmtVT = Amt.getValueType();
7069 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7070 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7071 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
7072 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
7073 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
7074 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7075 DAG.getConstant(-BitWidth, dl, AmtVT));
7076 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
7077 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7078 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
7079 SDValue OutOps[] = { OutLo, OutHi };
7080 return DAG.getMergeValues(OutOps, dl);
7083 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7084 EVT VT = Op.getValueType();
7086 unsigned BitWidth = VT.getSizeInBits();
7087 assert(Op.getNumOperands() == 3 &&
7088 VT == Op.getOperand(1).getValueType() &&
7091 // Expand into a bunch of logical ops. Note that these ops
7092 // depend on the PPC behavior for oversized shift amounts.
7093 SDValue Lo = Op.getOperand(0);
7094 SDValue Hi = Op.getOperand(1);
7095 SDValue Amt = Op.getOperand(2);
7096 EVT AmtVT = Amt.getValueType();
7098 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7099 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7100 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7101 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7102 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7103 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7104 DAG.getConstant(-BitWidth, dl, AmtVT));
7105 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
7106 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7107 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
7108 SDValue OutOps[] = { OutLo, OutHi };
7109 return DAG.getMergeValues(OutOps, dl);
7112 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
7114 EVT VT = Op.getValueType();
7115 unsigned BitWidth = VT.getSizeInBits();
7116 assert(Op.getNumOperands() == 3 &&
7117 VT == Op.getOperand(1).getValueType() &&
7120 // Expand into a bunch of logical ops, followed by a select_cc.
7121 SDValue Lo = Op.getOperand(0);
7122 SDValue Hi = Op.getOperand(1);
7123 SDValue Amt = Op.getOperand(2);
7124 EVT AmtVT = Amt.getValueType();
7126 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7127 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7128 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7129 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7130 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7131 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7132 DAG.getConstant(-BitWidth, dl, AmtVT));
7133 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
7134 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
7135 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
7136 Tmp4, Tmp6, ISD::SETLE);
7137 SDValue OutOps[] = { OutLo, OutHi };
7138 return DAG.getMergeValues(OutOps, dl);
7141 //===----------------------------------------------------------------------===//
7142 // Vector related lowering.
7145 /// BuildSplatI - Build a canonical splati of Val with an element size of
7146 /// SplatSize. Cast the result to VT.
7147 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7148 SelectionDAG &DAG, const SDLoc &dl) {
7149 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7151 static const MVT VTys[] = { // canonical VT to use for each size.
7152 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7155 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7157 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7161 EVT CanonicalVT = VTys[SplatSize-1];
7163 // Build a canonical splat for this value.
7164 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7167 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7168 /// specified intrinsic ID.
7169 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7170 const SDLoc &dl, EVT DestVT = MVT::Other) {
7171 if (DestVT == MVT::Other) DestVT = Op.getValueType();
7172 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7173 DAG.getConstant(IID, dl, MVT::i32), Op);
7176 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7177 /// specified intrinsic ID.
7178 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7179 SelectionDAG &DAG, const SDLoc &dl,
7180 EVT DestVT = MVT::Other) {
7181 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7182 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7183 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7186 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7187 /// specified intrinsic ID.
7188 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7189 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7190 EVT DestVT = MVT::Other) {
7191 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7192 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7193 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7196 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7197 /// amount. The result has the specified value type.
7198 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7199 SelectionDAG &DAG, const SDLoc &dl) {
7200 // Force LHS/RHS to be the right type.
7201 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7202 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7205 for (unsigned i = 0; i != 16; ++i)
7207 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7208 return DAG.getNode(ISD::BITCAST, dl, VT, T);
7211 /// Do we have an efficient pattern in a .td file for this node?
7213 /// \param V - pointer to the BuildVectorSDNode being matched
7214 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
7216 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
7217 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
7218 /// the opposite is true (expansion is beneficial) are:
7219 /// - The node builds a vector out of integers that are not 32 or 64-bits
7220 /// - The node builds a vector out of constants
7221 /// - The node is a "load-and-splat"
7222 /// In all other cases, we will choose to keep the BUILD_VECTOR.
7223 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
7224 bool HasDirectMove) {
7225 EVT VecVT = V->getValueType(0);
7226 bool RightType = VecVT == MVT::v2f64 || VecVT == MVT::v4f32 ||
7227 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
7231 bool IsSplat = true;
7232 bool IsLoad = false;
7233 SDValue Op0 = V->getOperand(0);
7235 // This function is called in a block that confirms the node is not a constant
7236 // splat. So a constant BUILD_VECTOR here means the vector is built out of
7237 // different constants.
7238 if (V->isConstant())
7240 for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
7241 if (V->getOperand(i).isUndef())
7243 // We want to expand nodes that represent load-and-splat even if the
7244 // loaded value is a floating point truncation or conversion to int.
7245 if (V->getOperand(i).getOpcode() == ISD::LOAD ||
7246 (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
7247 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7248 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
7249 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7250 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
7251 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
7253 // If the operands are different or the input is not a load and has more
7254 // uses than just this BV node, then it isn't a splat.
7255 if (V->getOperand(i) != Op0 ||
7256 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
7259 return !(IsSplat && IsLoad);
7262 // If this is a case we can't handle, return null and let the default
7263 // expansion code take care of it. If we CAN select this case, and if it
7264 // selects to a single instruction, return Op. Otherwise, if we can codegen
7265 // this case more efficiently than a constant pool load, lower it to the
7266 // sequence of ops that should be used.
7267 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7268 SelectionDAG &DAG) const {
7270 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7271 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7273 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7274 // We first build an i32 vector, load it into a QPX register,
7275 // then convert it to a floating-point vector and compare it
7276 // to a zero vector to get the boolean result.
7277 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7278 int FrameIdx = MFI.CreateStackObject(16, 16, false);
7279 MachinePointerInfo PtrInfo =
7280 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7281 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7282 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7284 assert(BVN->getNumOperands() == 4 &&
7285 "BUILD_VECTOR for v4i1 does not have 4 operands");
7287 bool IsConst = true;
7288 for (unsigned i = 0; i < 4; ++i) {
7289 if (BVN->getOperand(i).isUndef()) continue;
7290 if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7298 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7300 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7303 for (unsigned i = 0; i < 4; ++i) {
7304 if (BVN->getOperand(i).isUndef())
7305 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7306 else if (isNullConstant(BVN->getOperand(i)))
7312 Constant *CP = ConstantVector::get(CV);
7313 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7314 16 /* alignment */);
7316 SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7317 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7318 return DAG.getMemIntrinsicNode(
7319 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7320 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7323 SmallVector<SDValue, 4> Stores;
7324 for (unsigned i = 0; i < 4; ++i) {
7325 if (BVN->getOperand(i).isUndef()) continue;
7327 unsigned Offset = 4*i;
7328 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7329 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7331 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7332 if (StoreSize > 4) {
7334 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
7335 PtrInfo.getWithOffset(Offset), MVT::i32));
7337 SDValue StoreValue = BVN->getOperand(i);
7339 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7341 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
7342 PtrInfo.getWithOffset(Offset)));
7347 if (!Stores.empty())
7348 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7350 StoreChain = DAG.getEntryNode();
7352 // Now load from v4i32 into the QPX register; this will extend it to
7353 // v4i64 but not yet convert it to a floating point. Nevertheless, this
7354 // is typed as v4f64 because the QPX register integer states are not
7355 // explicitly represented.
7357 SDValue Ops[] = {StoreChain,
7358 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7360 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7362 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7363 dl, VTs, Ops, MVT::v4i32, PtrInfo);
7364 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7365 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7368 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7370 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7373 // All other QPX vectors are handled by generic code.
7374 if (Subtarget.hasQPX())
7377 // Check if this is a splat of a constant value.
7378 APInt APSplatBits, APSplatUndef;
7379 unsigned SplatBitSize;
7381 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7382 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7383 SplatBitSize > 32) {
7384 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
7385 // lowered to VSX instructions under certain conditions.
7386 // Without VSX, there is no pattern more efficient than expanding the node.
7387 if (Subtarget.hasVSX() &&
7388 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove()))
7393 unsigned SplatBits = APSplatBits.getZExtValue();
7394 unsigned SplatUndef = APSplatUndef.getZExtValue();
7395 unsigned SplatSize = SplatBitSize / 8;
7397 // First, handle single instruction cases.
7400 if (SplatBits == 0) {
7401 // Canonicalize all zero vectors to be v4i32.
7402 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7403 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7404 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7409 // We have XXSPLTIB for constant splats one byte wide
7410 if (Subtarget.hasP9Vector() && SplatSize == 1) {
7411 // This is a splat of 1-byte elements with some elements potentially undef.
7412 // Rather than trying to match undef in the SDAG patterns, ensure that all
7413 // elements are the same constant.
7414 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
7415 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
7417 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
7418 if (Op.getValueType() != MVT::v16i8)
7419 return DAG.getBitcast(Op.getValueType(), NewBV);
7425 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7426 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7428 if (SextVal >= -16 && SextVal <= 15)
7429 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7431 // Two instruction sequences.
7433 // If this value is in the range [-32,30] and is even, use:
7434 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7435 // If this value is in the range [17,31] and is odd, use:
7436 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7437 // If this value is in the range [-31,-17] and is odd, use:
7438 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7439 // Note the last two are three-instruction sequences.
7440 if (SextVal >= -32 && SextVal <= 31) {
7441 // To avoid having these optimizations undone by constant folding,
7442 // we convert to a pseudo that will be expanded later into one of
7444 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7445 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7446 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7447 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7448 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7449 if (VT == Op.getValueType())
7452 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7455 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
7456 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
7458 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7459 // Make -1 and vspltisw -1:
7460 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7462 // Make the VSLW intrinsic, computing 0x8000_0000.
7463 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7466 // xor by OnesV to invert it.
7467 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7468 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7471 // Check to see if this is a wide variety of vsplti*, binop self cases.
7472 static const signed char SplatCsts[] = {
7473 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7474 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7477 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7478 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7479 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
7480 int i = SplatCsts[idx];
7482 // Figure out what shift amount will be used by altivec if shifted by i in
7484 unsigned TypeShiftAmt = i & (SplatBitSize-1);
7486 // vsplti + shl self.
7487 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7488 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7489 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7490 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7491 Intrinsic::ppc_altivec_vslw
7493 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7494 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7497 // vsplti + srl self.
7498 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7499 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7500 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7501 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7502 Intrinsic::ppc_altivec_vsrw
7504 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7505 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7508 // vsplti + sra self.
7509 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7510 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7511 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7512 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7513 Intrinsic::ppc_altivec_vsraw
7515 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7516 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7519 // vsplti + rol self.
7520 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7521 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7522 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7523 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7524 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7525 Intrinsic::ppc_altivec_vrlw
7527 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7528 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7531 // t = vsplti c, result = vsldoi t, t, 1
7532 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7533 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7534 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7535 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7537 // t = vsplti c, result = vsldoi t, t, 2
7538 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7539 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7540 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7541 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7543 // t = vsplti c, result = vsldoi t, t, 3
7544 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7545 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7546 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7547 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7554 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7555 /// the specified operations to build the shuffle.
7556 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7557 SDValue RHS, SelectionDAG &DAG,
7559 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7560 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7561 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7564 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7576 if (OpNum == OP_COPY) {
7577 if (LHSID == (1*9+2)*9+3) return LHS;
7578 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7582 SDValue OpLHS, OpRHS;
7583 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7584 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7588 default: llvm_unreachable("Unknown i32 permute!");
7590 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
7591 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7592 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
7593 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7596 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7597 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7598 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7599 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7602 for (unsigned i = 0; i != 16; ++i)
7603 ShufIdxs[i] = (i&3)+0;
7606 for (unsigned i = 0; i != 16; ++i)
7607 ShufIdxs[i] = (i&3)+4;
7610 for (unsigned i = 0; i != 16; ++i)
7611 ShufIdxs[i] = (i&3)+8;
7614 for (unsigned i = 0; i != 16; ++i)
7615 ShufIdxs[i] = (i&3)+12;
7618 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7620 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7622 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7624 EVT VT = OpLHS.getValueType();
7625 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7626 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7627 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7628 return DAG.getNode(ISD::BITCAST, dl, VT, T);
7631 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
7632 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
7633 /// return the code it can be lowered into. Worst case, it can always be
7634 /// lowered into a vperm.
7635 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7636 SelectionDAG &DAG) const {
7638 SDValue V1 = Op.getOperand(0);
7639 SDValue V2 = Op.getOperand(1);
7640 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7641 EVT VT = Op.getValueType();
7642 bool isLittleEndian = Subtarget.isLittleEndian();
7644 unsigned ShiftElts, InsertAtByte;
7646 if (Subtarget.hasP9Vector() &&
7647 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
7651 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7652 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
7654 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
7655 DAG.getConstant(ShiftElts, dl, MVT::i32));
7656 SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Shl,
7657 DAG.getConstant(InsertAtByte, dl, MVT::i32));
7658 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7660 SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Conv2,
7661 DAG.getConstant(InsertAtByte, dl, MVT::i32));
7662 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7665 if (Subtarget.hasVSX()) {
7666 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
7667 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
7669 // If the source for the shuffle is a scalar_to_vector that came from a
7670 // 32-bit load, it will have used LXVWSX so we don't need to splat again.
7671 if (Subtarget.hasP9Vector() &&
7672 ((isLittleEndian && SplatIdx == 3) ||
7673 (!isLittleEndian && SplatIdx == 0))) {
7674 SDValue Src = V1.getOperand(0);
7675 if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7676 Src.getOperand(0).getOpcode() == ISD::LOAD &&
7677 Src.getOperand(0).hasOneUse())
7680 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7681 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
7682 DAG.getConstant(SplatIdx, dl, MVT::i32));
7683 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
7686 // Left shifts of 8 bytes are actually swaps. Convert accordingly.
7687 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
7688 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7689 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
7690 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
7694 if (Subtarget.hasQPX()) {
7695 if (VT.getVectorNumElements() != 4)
7698 if (V2.isUndef()) V2 = V1;
7700 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7701 if (AlignIdx != -1) {
7702 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7703 DAG.getConstant(AlignIdx, dl, MVT::i32));
7704 } else if (SVOp->isSplat()) {
7705 int SplatIdx = SVOp->getSplatIndex();
7706 if (SplatIdx >= 4) {
7711 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7712 DAG.getConstant(SplatIdx, dl, MVT::i32));
7715 // Lower this into a qvgpci/qvfperm pair.
7717 // Compute the qvgpci literal
7719 for (unsigned i = 0; i < 4; ++i) {
7720 int m = SVOp->getMaskElt(i);
7721 unsigned mm = m >= 0 ? (unsigned) m : i;
7722 idx |= mm << (3-i)*3;
7725 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7726 DAG.getConstant(idx, dl, MVT::i32));
7727 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7730 // Cases that are handled by instructions that take permute immediates
7731 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7732 // selected by the instruction selector.
7734 if (PPC::isSplatShuffleMask(SVOp, 1) ||
7735 PPC::isSplatShuffleMask(SVOp, 2) ||
7736 PPC::isSplatShuffleMask(SVOp, 4) ||
7737 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7738 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7739 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7740 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7741 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7742 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7743 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7744 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7745 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
7746 (Subtarget.hasP8Altivec() && (
7747 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7748 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
7749 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
7754 // Altivec has a variety of "shuffle immediates" that take two vector inputs
7755 // and produce a fixed permutation. If any of these match, do not lower to
7757 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7758 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7759 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7760 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7761 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7762 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7763 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7764 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7765 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7766 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7767 (Subtarget.hasP8Altivec() && (
7768 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7769 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
7770 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
7773 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
7774 // perfect shuffle table to emit an optimal matching sequence.
7775 ArrayRef<int> PermMask = SVOp->getMask();
7777 unsigned PFIndexes[4];
7778 bool isFourElementShuffle = true;
7779 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7780 unsigned EltNo = 8; // Start out undef.
7781 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
7782 if (PermMask[i*4+j] < 0)
7783 continue; // Undef, ignore it.
7785 unsigned ByteSource = PermMask[i*4+j];
7786 if ((ByteSource & 3) != j) {
7787 isFourElementShuffle = false;
7792 EltNo = ByteSource/4;
7793 } else if (EltNo != ByteSource/4) {
7794 isFourElementShuffle = false;
7798 PFIndexes[i] = EltNo;
7801 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7802 // perfect shuffle vector to determine if it is cost effective to do this as
7803 // discrete instructions, or whether we should use a vperm.
7804 // For now, we skip this for little endian until such time as we have a
7805 // little-endian perfect shuffle table.
7806 if (isFourElementShuffle && !isLittleEndian) {
7807 // Compute the index in the perfect shuffle table.
7808 unsigned PFTableIndex =
7809 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7811 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7812 unsigned Cost = (PFEntry >> 30);
7814 // Determining when to avoid vperm is tricky. Many things affect the cost
7815 // of vperm, particularly how many times the perm mask needs to be computed.
7816 // For example, if the perm mask can be hoisted out of a loop or is already
7817 // used (perhaps because there are multiple permutes with the same shuffle
7818 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
7819 // the loop requires an extra register.
7821 // As a compromise, we only emit discrete instructions if the shuffle can be
7822 // generated in 3 or fewer operations. When we have loop information
7823 // available, if this block is within a loop, we should avoid using vperm
7824 // for 3-operation perms and use a constant pool load instead.
7826 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7829 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7830 // vector that will get spilled to the constant pool.
7831 if (V2.isUndef()) V2 = V1;
7833 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7834 // that it is in input element units, not in bytes. Convert now.
7836 // For little endian, the order of the input vectors is reversed, and
7837 // the permutation mask is complemented with respect to 31. This is
7838 // necessary to produce proper semantics with the big-endian-biased vperm
7840 EVT EltVT = V1.getValueType().getVectorElementType();
7841 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7843 SmallVector<SDValue, 16> ResultMask;
7844 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7845 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7847 for (unsigned j = 0; j != BytesPerElement; ++j)
7849 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7852 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7856 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
7858 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7861 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7865 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
7866 /// vector comparison. If it is, return true and fill in Opc/isDot with
7867 /// information about the intrinsic.
7868 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
7869 bool &isDot, const PPCSubtarget &Subtarget) {
7870 unsigned IntrinsicID =
7871 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7874 switch (IntrinsicID) {
7877 // Comparison predicates.
7878 case Intrinsic::ppc_altivec_vcmpbfp_p:
7882 case Intrinsic::ppc_altivec_vcmpeqfp_p:
7886 case Intrinsic::ppc_altivec_vcmpequb_p:
7890 case Intrinsic::ppc_altivec_vcmpequh_p:
7894 case Intrinsic::ppc_altivec_vcmpequw_p:
7898 case Intrinsic::ppc_altivec_vcmpequd_p:
7899 if (Subtarget.hasP8Altivec()) {
7905 case Intrinsic::ppc_altivec_vcmpneb_p:
7906 case Intrinsic::ppc_altivec_vcmpneh_p:
7907 case Intrinsic::ppc_altivec_vcmpnew_p:
7908 case Intrinsic::ppc_altivec_vcmpnezb_p:
7909 case Intrinsic::ppc_altivec_vcmpnezh_p:
7910 case Intrinsic::ppc_altivec_vcmpnezw_p:
7911 if (Subtarget.hasP9Altivec()) {
7912 switch (IntrinsicID) {
7914 llvm_unreachable("Unknown comparison intrinsic.");
7915 case Intrinsic::ppc_altivec_vcmpneb_p:
7918 case Intrinsic::ppc_altivec_vcmpneh_p:
7921 case Intrinsic::ppc_altivec_vcmpnew_p:
7924 case Intrinsic::ppc_altivec_vcmpnezb_p:
7927 case Intrinsic::ppc_altivec_vcmpnezh_p:
7930 case Intrinsic::ppc_altivec_vcmpnezw_p:
7938 case Intrinsic::ppc_altivec_vcmpgefp_p:
7942 case Intrinsic::ppc_altivec_vcmpgtfp_p:
7946 case Intrinsic::ppc_altivec_vcmpgtsb_p:
7950 case Intrinsic::ppc_altivec_vcmpgtsh_p:
7954 case Intrinsic::ppc_altivec_vcmpgtsw_p:
7958 case Intrinsic::ppc_altivec_vcmpgtsd_p:
7959 if (Subtarget.hasP8Altivec()) {
7965 case Intrinsic::ppc_altivec_vcmpgtub_p:
7969 case Intrinsic::ppc_altivec_vcmpgtuh_p:
7973 case Intrinsic::ppc_altivec_vcmpgtuw_p:
7977 case Intrinsic::ppc_altivec_vcmpgtud_p:
7978 if (Subtarget.hasP8Altivec()) {
7985 // VSX predicate comparisons use the same infrastructure
7986 case Intrinsic::ppc_vsx_xvcmpeqdp_p:
7987 case Intrinsic::ppc_vsx_xvcmpgedp_p:
7988 case Intrinsic::ppc_vsx_xvcmpgtdp_p:
7989 case Intrinsic::ppc_vsx_xvcmpeqsp_p:
7990 case Intrinsic::ppc_vsx_xvcmpgesp_p:
7991 case Intrinsic::ppc_vsx_xvcmpgtsp_p:
7992 if (Subtarget.hasVSX()) {
7993 switch (IntrinsicID) {
7994 case Intrinsic::ppc_vsx_xvcmpeqdp_p:
7997 case Intrinsic::ppc_vsx_xvcmpgedp_p:
8000 case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8003 case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8006 case Intrinsic::ppc_vsx_xvcmpgesp_p:
8009 case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8018 // Normal Comparisons.
8019 case Intrinsic::ppc_altivec_vcmpbfp:
8022 case Intrinsic::ppc_altivec_vcmpeqfp:
8025 case Intrinsic::ppc_altivec_vcmpequb:
8028 case Intrinsic::ppc_altivec_vcmpequh:
8031 case Intrinsic::ppc_altivec_vcmpequw:
8034 case Intrinsic::ppc_altivec_vcmpequd:
8035 if (Subtarget.hasP8Altivec())
8040 case Intrinsic::ppc_altivec_vcmpneb:
8041 case Intrinsic::ppc_altivec_vcmpneh:
8042 case Intrinsic::ppc_altivec_vcmpnew:
8043 case Intrinsic::ppc_altivec_vcmpnezb:
8044 case Intrinsic::ppc_altivec_vcmpnezh:
8045 case Intrinsic::ppc_altivec_vcmpnezw:
8046 if (Subtarget.hasP9Altivec())
8047 switch (IntrinsicID) {
8049 llvm_unreachable("Unknown comparison intrinsic.");
8050 case Intrinsic::ppc_altivec_vcmpneb:
8053 case Intrinsic::ppc_altivec_vcmpneh:
8056 case Intrinsic::ppc_altivec_vcmpnew:
8059 case Intrinsic::ppc_altivec_vcmpnezb:
8062 case Intrinsic::ppc_altivec_vcmpnezh:
8065 case Intrinsic::ppc_altivec_vcmpnezw:
8072 case Intrinsic::ppc_altivec_vcmpgefp:
8075 case Intrinsic::ppc_altivec_vcmpgtfp:
8078 case Intrinsic::ppc_altivec_vcmpgtsb:
8081 case Intrinsic::ppc_altivec_vcmpgtsh:
8084 case Intrinsic::ppc_altivec_vcmpgtsw:
8087 case Intrinsic::ppc_altivec_vcmpgtsd:
8088 if (Subtarget.hasP8Altivec())
8093 case Intrinsic::ppc_altivec_vcmpgtub:
8096 case Intrinsic::ppc_altivec_vcmpgtuh:
8099 case Intrinsic::ppc_altivec_vcmpgtuw:
8102 case Intrinsic::ppc_altivec_vcmpgtud:
8103 if (Subtarget.hasP8Altivec())
8112 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
8113 /// lower, do it, otherwise return null.
8114 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
8115 SelectionDAG &DAG) const {
8116 unsigned IntrinsicID =
8117 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8119 if (IntrinsicID == Intrinsic::thread_pointer) {
8120 // Reads the thread pointer register, used for __builtin_thread_pointer.
8121 bool is64bit = Subtarget.isPPC64();
8122 return DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
8123 is64bit ? MVT::i64 : MVT::i32);
8126 // If this is a lowered altivec predicate compare, CompareOpc is set to the
8127 // opcode number of the comparison.
8131 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
8132 return SDValue(); // Don't custom lower most intrinsics.
8134 // If this is a non-dot comparison, make the VCMP node and we are done.
8136 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
8137 Op.getOperand(1), Op.getOperand(2),
8138 DAG.getConstant(CompareOpc, dl, MVT::i32));
8139 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
8142 // Create the PPCISD altivec 'dot' comparison node.
8144 Op.getOperand(2), // LHS
8145 Op.getOperand(3), // RHS
8146 DAG.getConstant(CompareOpc, dl, MVT::i32)
8148 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
8149 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8151 // Now that we have the comparison, emit a copy from the CR to a GPR.
8152 // This is flagged to the above dot comparison.
8153 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
8154 DAG.getRegister(PPC::CR6, MVT::i32),
8155 CompNode.getValue(1));
8157 // Unpack the result based on how the target uses it.
8158 unsigned BitNo; // Bit # of CR6.
8159 bool InvertBit; // Invert result?
8160 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
8161 default: // Can't happen, don't crash on invalid number though.
8162 case 0: // Return the value of the EQ bit of CR6.
8163 BitNo = 0; InvertBit = false;
8165 case 1: // Return the inverted value of the EQ bit of CR6.
8166 BitNo = 0; InvertBit = true;
8168 case 2: // Return the value of the LT bit of CR6.
8169 BitNo = 2; InvertBit = false;
8171 case 3: // Return the inverted value of the LT bit of CR6.
8172 BitNo = 2; InvertBit = true;
8176 // Shift the bit into the low position.
8177 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
8178 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
8180 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
8181 DAG.getConstant(1, dl, MVT::i32));
8183 // If we are supposed to, toggle the bit.
8185 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
8186 DAG.getConstant(1, dl, MVT::i32));
8190 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
8191 SelectionDAG &DAG) const {
8193 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
8194 // instructions), but for smaller types, we need to first extend up to v2i32
8195 // before doing going farther.
8196 if (Op.getValueType() == MVT::v2i64) {
8197 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
8198 if (ExtVT != MVT::v2i32) {
8199 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
8200 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
8201 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
8202 ExtVT.getVectorElementType(), 4)));
8203 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
8204 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
8205 DAG.getValueType(MVT::v2i32));
8214 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
8215 SelectionDAG &DAG) const {
8217 // Create a stack slot that is 16-byte aligned.
8218 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8219 int FrameIdx = MFI.CreateStackObject(16, 16, false);
8220 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8221 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8223 // Store the input value into Value#0 of the stack slot.
8224 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8225 MachinePointerInfo());
8227 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
8230 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8231 SelectionDAG &DAG) const {
8232 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
8233 "Should only be called for ISD::INSERT_VECTOR_ELT");
8234 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
8235 // We have legal lowering for constant indices but not for variable ones.
8241 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8242 SelectionDAG &DAG) const {
8244 SDNode *N = Op.getNode();
8246 assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
8247 "Unknown extract_vector_elt type");
8249 SDValue Value = N->getOperand(0);
8251 // The first part of this is like the store lowering except that we don't
8252 // need to track the chain.
8254 // The values are now known to be -1 (false) or 1 (true). To convert this
8255 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8256 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8257 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8259 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8260 // understand how to form the extending load.
8261 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8263 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8265 // Now convert to an integer and store.
8266 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8267 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8270 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8271 int FrameIdx = MFI.CreateStackObject(16, 16, false);
8272 MachinePointerInfo PtrInfo =
8273 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8274 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8275 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8277 SDValue StoreChain = DAG.getEntryNode();
8278 SDValue Ops[] = {StoreChain,
8279 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8281 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8283 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8284 dl, VTs, Ops, MVT::v4i32, PtrInfo);
8286 // Extract the value requested.
8287 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8288 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8289 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8292 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
8294 if (!Subtarget.useCRBits())
8297 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
8300 /// Lowering for QPX v4i1 loads
8301 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
8302 SelectionDAG &DAG) const {
8304 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
8305 SDValue LoadChain = LN->getChain();
8306 SDValue BasePtr = LN->getBasePtr();
8308 if (Op.getValueType() == MVT::v4f64 ||
8309 Op.getValueType() == MVT::v4f32) {
8310 EVT MemVT = LN->getMemoryVT();
8311 unsigned Alignment = LN->getAlignment();
8313 // If this load is properly aligned, then it is legal.
8314 if (Alignment >= MemVT.getStoreSize())
8317 EVT ScalarVT = Op.getValueType().getScalarType(),
8318 ScalarMemVT = MemVT.getScalarType();
8319 unsigned Stride = ScalarMemVT.getStoreSize();
8321 SDValue Vals[4], LoadChains[4];
8322 for (unsigned Idx = 0; Idx < 4; ++Idx) {
8324 if (ScalarVT != ScalarMemVT)
8325 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
8327 LN->getPointerInfo().getWithOffset(Idx * Stride),
8328 ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8329 LN->getMemOperand()->getFlags(), LN->getAAInfo());
8331 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
8332 LN->getPointerInfo().getWithOffset(Idx * Stride),
8333 MinAlign(Alignment, Idx * Stride),
8334 LN->getMemOperand()->getFlags(), LN->getAAInfo());
8336 if (Idx == 0 && LN->isIndexed()) {
8337 assert(LN->getAddressingMode() == ISD::PRE_INC &&
8338 "Unknown addressing mode on vector load");
8339 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
8340 LN->getAddressingMode());
8344 LoadChains[Idx] = Load.getValue(1);
8346 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8347 DAG.getConstant(Stride, dl,
8348 BasePtr.getValueType()));
8351 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8352 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
8354 if (LN->isIndexed()) {
8355 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
8356 return DAG.getMergeValues(RetOps, dl);
8359 SDValue RetOps[] = { Value, TF };
8360 return DAG.getMergeValues(RetOps, dl);
8363 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
8364 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
8366 // To lower v4i1 from a byte array, we load the byte elements of the
8367 // vector and then reuse the BUILD_VECTOR logic.
8369 SDValue VectElmts[4], VectElmtChains[4];
8370 for (unsigned i = 0; i < 4; ++i) {
8371 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8372 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8374 VectElmts[i] = DAG.getExtLoad(
8375 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
8376 LN->getPointerInfo().getWithOffset(i), MVT::i8,
8377 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
8378 VectElmtChains[i] = VectElmts[i].getValue(1);
8381 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
8382 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
8384 SDValue RVals[] = { Value, LoadChain };
8385 return DAG.getMergeValues(RVals, dl);
8388 /// Lowering for QPX v4i1 stores
8389 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
8390 SelectionDAG &DAG) const {
8392 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
8393 SDValue StoreChain = SN->getChain();
8394 SDValue BasePtr = SN->getBasePtr();
8395 SDValue Value = SN->getValue();
8397 if (Value.getValueType() == MVT::v4f64 ||
8398 Value.getValueType() == MVT::v4f32) {
8399 EVT MemVT = SN->getMemoryVT();
8400 unsigned Alignment = SN->getAlignment();
8402 // If this store is properly aligned, then it is legal.
8403 if (Alignment >= MemVT.getStoreSize())
8406 EVT ScalarVT = Value.getValueType().getScalarType(),
8407 ScalarMemVT = MemVT.getScalarType();
8408 unsigned Stride = ScalarMemVT.getStoreSize();
8411 for (unsigned Idx = 0; Idx < 4; ++Idx) {
8412 SDValue Ex = DAG.getNode(
8413 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
8414 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
8416 if (ScalarVT != ScalarMemVT)
8418 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
8419 SN->getPointerInfo().getWithOffset(Idx * Stride),
8420 ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8421 SN->getMemOperand()->getFlags(), SN->getAAInfo());
8423 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
8424 SN->getPointerInfo().getWithOffset(Idx * Stride),
8425 MinAlign(Alignment, Idx * Stride),
8426 SN->getMemOperand()->getFlags(), SN->getAAInfo());
8428 if (Idx == 0 && SN->isIndexed()) {
8429 assert(SN->getAddressingMode() == ISD::PRE_INC &&
8430 "Unknown addressing mode on vector store");
8431 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
8432 SN->getAddressingMode());
8435 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8436 DAG.getConstant(Stride, dl,
8437 BasePtr.getValueType()));
8438 Stores[Idx] = Store;
8441 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8443 if (SN->isIndexed()) {
8444 SDValue RetOps[] = { TF, Stores[0].getValue(1) };
8445 return DAG.getMergeValues(RetOps, dl);
8451 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
8452 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
8454 // The values are now known to be -1 (false) or 1 (true). To convert this
8455 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8456 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8457 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8459 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8460 // understand how to form the extending load.
8461 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8463 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8465 // Now convert to an integer and store.
8466 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8467 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8470 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8471 int FrameIdx = MFI.CreateStackObject(16, 16, false);
8472 MachinePointerInfo PtrInfo =
8473 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8474 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8475 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8477 SDValue Ops[] = {StoreChain,
8478 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8480 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8482 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8483 dl, VTs, Ops, MVT::v4i32, PtrInfo);
8485 // Move data into the byte array.
8486 SDValue Loads[4], LoadChains[4];
8487 for (unsigned i = 0; i < 4; ++i) {
8488 unsigned Offset = 4*i;
8489 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8490 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8492 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
8493 PtrInfo.getWithOffset(Offset));
8494 LoadChains[i] = Loads[i].getValue(1);
8497 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8500 for (unsigned i = 0; i < 4; ++i) {
8501 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8502 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8504 Stores[i] = DAG.getTruncStore(
8505 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
8506 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
8510 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8515 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
8517 if (Op.getValueType() == MVT::v4i32) {
8518 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8520 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
8521 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
8523 SDValue RHSSwap = // = vrlw RHS, 16
8524 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
8526 // Shrinkify inputs to v8i16.
8527 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
8528 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
8529 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
8531 // Low parts multiplied together, generating 32-bit results (we ignore the
8533 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
8534 LHS, RHS, DAG, dl, MVT::v4i32);
8536 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
8537 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
8538 // Shift the high parts up 16 bits.
8539 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
8541 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
8542 } else if (Op.getValueType() == MVT::v8i16) {
8543 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8545 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
8547 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
8548 LHS, RHS, Zero, DAG, dl);
8549 } else if (Op.getValueType() == MVT::v16i8) {
8550 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8551 bool isLittleEndian = Subtarget.isLittleEndian();
8553 // Multiply the even 8-bit parts, producing 16-bit sums.
8554 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
8555 LHS, RHS, DAG, dl, MVT::v8i16);
8556 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
8558 // Multiply the odd 8-bit parts, producing 16-bit sums.
8559 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
8560 LHS, RHS, DAG, dl, MVT::v8i16);
8561 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
8563 // Merge the results together. Because vmuleub and vmuloub are
8564 // instructions with a big-endian bias, we must reverse the
8565 // element numbering and reverse the meaning of "odd" and "even"
8566 // when generating little endian code.
8568 for (unsigned i = 0; i != 8; ++i) {
8569 if (isLittleEndian) {
8571 Ops[i*2+1] = 2*i+16;
8574 Ops[i*2+1] = 2*i+1+16;
8578 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
8580 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
8582 llvm_unreachable("Unknown mul to lower!");
8586 /// LowerOperation - Provide custom lowering hooks for some operations.
8588 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8589 switch (Op.getOpcode()) {
8590 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
8591 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8592 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
8593 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8594 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8595 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
8596 case ISD::SETCC: return LowerSETCC(Op, DAG);
8597 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
8598 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
8600 return LowerVASTART(Op, DAG);
8603 return LowerVAARG(Op, DAG);
8606 return LowerVACOPY(Op, DAG);
8608 case ISD::STACKRESTORE:
8609 return LowerSTACKRESTORE(Op, DAG);
8611 case ISD::DYNAMIC_STACKALLOC:
8612 return LowerDYNAMIC_STACKALLOC(Op, DAG);
8614 case ISD::GET_DYNAMIC_AREA_OFFSET:
8615 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
8617 case ISD::EH_DWARF_CFA:
8618 return LowerEH_DWARF_CFA(Op, DAG);
8620 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
8621 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
8623 case ISD::LOAD: return LowerLOAD(Op, DAG);
8624 case ISD::STORE: return LowerSTORE(Op, DAG);
8625 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
8626 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
8627 case ISD::FP_TO_UINT:
8628 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
8630 case ISD::UINT_TO_FP:
8631 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
8632 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
8634 // Lower 64-bit shifts.
8635 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
8636 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
8637 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
8639 // Vector-related lowering.
8640 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
8641 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
8642 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8643 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
8644 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
8645 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8646 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8647 case ISD::MUL: return LowerMUL(Op, DAG);
8649 // For counter-based loop handling.
8650 case ISD::INTRINSIC_W_CHAIN: return SDValue();
8652 // Frame & Return address.
8653 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
8654 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
8658 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
8659 SmallVectorImpl<SDValue>&Results,
8660 SelectionDAG &DAG) const {
8662 switch (N->getOpcode()) {
8664 llvm_unreachable("Do not know how to custom type legalize this operation!");
8665 case ISD::READCYCLECOUNTER: {
8666 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8667 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
8669 Results.push_back(RTB);
8670 Results.push_back(RTB.getValue(1));
8671 Results.push_back(RTB.getValue(2));
8674 case ISD::INTRINSIC_W_CHAIN: {
8675 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
8676 Intrinsic::ppc_is_decremented_ctr_nonzero)
8679 assert(N->getValueType(0) == MVT::i1 &&
8680 "Unexpected result type for CTR decrement intrinsic");
8681 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
8682 N->getValueType(0));
8683 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
8684 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
8687 Results.push_back(NewInt);
8688 Results.push_back(NewInt.getValue(1));
8692 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
8695 EVT VT = N->getValueType(0);
8697 if (VT == MVT::i64) {
8698 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
8700 Results.push_back(NewNode);
8701 Results.push_back(NewNode.getValue(1));
8705 case ISD::FP_ROUND_INREG: {
8706 assert(N->getValueType(0) == MVT::ppcf128);
8707 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
8708 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8709 MVT::f64, N->getOperand(0),
8710 DAG.getIntPtrConstant(0, dl));
8711 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8712 MVT::f64, N->getOperand(0),
8713 DAG.getIntPtrConstant(1, dl));
8715 // Add the two halves of the long double in round-to-zero mode.
8716 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8718 // We know the low half is about to be thrown away, so just use something
8720 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
8724 case ISD::FP_TO_SINT:
8725 case ISD::FP_TO_UINT:
8726 // LowerFP_TO_INT() can only handle f32 and f64.
8727 if (N->getOperand(0).getValueType() == MVT::ppcf128)
8729 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
8734 //===----------------------------------------------------------------------===//
8735 // Other Lowering Code
8736 //===----------------------------------------------------------------------===//
8738 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
8739 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8740 Function *Func = Intrinsic::getDeclaration(M, Id);
8741 return Builder.CreateCall(Func, {});
8744 // The mappings for emitLeading/TrailingFence is taken from
8745 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
8746 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
8747 AtomicOrdering Ord, bool IsStore,
8748 bool IsLoad) const {
8749 if (Ord == AtomicOrdering::SequentiallyConsistent)
8750 return callIntrinsic(Builder, Intrinsic::ppc_sync);
8751 if (isReleaseOrStronger(Ord))
8752 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8756 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
8757 AtomicOrdering Ord, bool IsStore,
8758 bool IsLoad) const {
8759 if (IsLoad && isAcquireOrStronger(Ord))
8760 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8761 // FIXME: this is too conservative, a dependent branch + isync is enough.
8762 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
8763 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
8764 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
8769 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
8770 unsigned AtomicSize,
8773 unsigned CmpPred) const {
8774 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8775 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8777 auto LoadMnemonic = PPC::LDARX;
8778 auto StoreMnemonic = PPC::STDCX;
8779 switch (AtomicSize) {
8781 llvm_unreachable("Unexpected size of atomic entity");
8783 LoadMnemonic = PPC::LBARX;
8784 StoreMnemonic = PPC::STBCX;
8785 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8788 LoadMnemonic = PPC::LHARX;
8789 StoreMnemonic = PPC::STHCX;
8790 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8793 LoadMnemonic = PPC::LWARX;
8794 StoreMnemonic = PPC::STWCX;
8797 LoadMnemonic = PPC::LDARX;
8798 StoreMnemonic = PPC::STDCX;
8802 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8803 MachineFunction *F = BB->getParent();
8804 MachineFunction::iterator It = ++BB->getIterator();
8806 unsigned dest = MI.getOperand(0).getReg();
8807 unsigned ptrA = MI.getOperand(1).getReg();
8808 unsigned ptrB = MI.getOperand(2).getReg();
8809 unsigned incr = MI.getOperand(3).getReg();
8810 DebugLoc dl = MI.getDebugLoc();
8812 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8813 MachineBasicBlock *loop2MBB =
8814 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8815 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8816 F->insert(It, loopMBB);
8818 F->insert(It, loop2MBB);
8819 F->insert(It, exitMBB);
8820 exitMBB->splice(exitMBB->begin(), BB,
8821 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8822 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8824 MachineRegisterInfo &RegInfo = F->getRegInfo();
8825 unsigned TmpReg = (!BinOpcode) ? incr :
8826 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
8827 : &PPC::GPRCRegClass);
8831 // fallthrough --> loopMBB
8832 BB->addSuccessor(loopMBB);
8835 // l[wd]arx dest, ptr
8836 // add r0, dest, incr
8837 // st[wd]cx. r0, ptr
8839 // fallthrough --> exitMBB
8843 // l[wd]arx dest, ptr
8844 // cmpl?[wd] incr, dest
8847 // st[wd]cx. dest, ptr
8849 // fallthrough --> exitMBB
8852 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8853 .addReg(ptrA).addReg(ptrB);
8855 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
8857 // Signed comparisons of byte or halfword values must be sign-extended.
8858 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
8859 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8860 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
8861 ExtReg).addReg(dest);
8862 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8863 .addReg(incr).addReg(ExtReg);
8865 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8866 .addReg(incr).addReg(dest);
8868 BuildMI(BB, dl, TII->get(PPC::BCC))
8869 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
8870 BB->addSuccessor(loop2MBB);
8871 BB->addSuccessor(exitMBB);
8874 BuildMI(BB, dl, TII->get(StoreMnemonic))
8875 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
8876 BuildMI(BB, dl, TII->get(PPC::BCC))
8877 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8878 BB->addSuccessor(loopMBB);
8879 BB->addSuccessor(exitMBB);
8888 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI,
8889 MachineBasicBlock *BB,
8890 bool is8bit, // operation
8893 unsigned CmpPred) const {
8894 // If we support part-word atomic mnemonics, just use them
8895 if (Subtarget.hasPartwordAtomics())
8896 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode,
8897 CmpOpcode, CmpPred);
8899 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8900 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8901 // In 64 bit mode we have to use 64 bits for addresses, even though the
8902 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
8903 // registers without caring whether they're 32 or 64, but here we're
8904 // doing actual arithmetic on the addresses.
8905 bool is64bit = Subtarget.isPPC64();
8906 bool isLittleEndian = Subtarget.isLittleEndian();
8907 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8909 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8910 MachineFunction *F = BB->getParent();
8911 MachineFunction::iterator It = ++BB->getIterator();
8913 unsigned dest = MI.getOperand(0).getReg();
8914 unsigned ptrA = MI.getOperand(1).getReg();
8915 unsigned ptrB = MI.getOperand(2).getReg();
8916 unsigned incr = MI.getOperand(3).getReg();
8917 DebugLoc dl = MI.getDebugLoc();
8919 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8920 MachineBasicBlock *loop2MBB =
8921 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8922 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8923 F->insert(It, loopMBB);
8925 F->insert(It, loop2MBB);
8926 F->insert(It, exitMBB);
8927 exitMBB->splice(exitMBB->begin(), BB,
8928 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8929 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8931 MachineRegisterInfo &RegInfo = F->getRegInfo();
8932 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8933 : &PPC::GPRCRegClass;
8934 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8935 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8937 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
8938 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
8939 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8940 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8941 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8942 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8943 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8944 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8945 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8947 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8951 // fallthrough --> loopMBB
8952 BB->addSuccessor(loopMBB);
8954 // The 4-byte load must be aligned, while a char or short may be
8955 // anywhere in the word. Hence all this nasty bookkeeping code.
8956 // add ptr1, ptrA, ptrB [copy if ptrA==0]
8957 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8958 // xori shift, shift1, 24 [16]
8959 // rlwinm ptr, ptr1, 0, 0, 29
8960 // slw incr2, incr, shift
8961 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8962 // slw mask, mask2, shift
8964 // lwarx tmpDest, ptr
8965 // add tmp, tmpDest, incr2
8966 // andc tmp2, tmpDest, mask
8967 // and tmp3, tmp, mask
8968 // or tmp4, tmp3, tmp2
8971 // fallthrough --> exitMBB
8972 // srw dest, tmpDest, shift
8973 if (ptrA != ZeroReg) {
8974 Ptr1Reg = RegInfo.createVirtualRegister(RC);
8975 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8976 .addReg(ptrA).addReg(ptrB);
8980 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8981 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8982 if (!isLittleEndian)
8983 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8984 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8986 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8987 .addReg(Ptr1Reg).addImm(0).addImm(61);
8989 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8990 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8991 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
8992 .addReg(incr).addReg(ShiftReg);
8994 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8996 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8997 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
8999 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9000 .addReg(Mask2Reg).addReg(ShiftReg);
9003 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9004 .addReg(ZeroReg).addReg(PtrReg);
9006 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
9007 .addReg(Incr2Reg).addReg(TmpDestReg);
9008 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
9009 .addReg(TmpDestReg).addReg(MaskReg);
9010 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
9011 .addReg(TmpReg).addReg(MaskReg);
9013 // For unsigned comparisons, we can directly compare the shifted values.
9014 // For signed comparisons we shift and sign extend.
9015 unsigned SReg = RegInfo.createVirtualRegister(RC);
9016 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg)
9017 .addReg(TmpDestReg).addReg(MaskReg);
9018 unsigned ValueReg = SReg;
9019 unsigned CmpReg = Incr2Reg;
9020 if (CmpOpcode == PPC::CMPW) {
9021 ValueReg = RegInfo.createVirtualRegister(RC);
9022 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
9023 .addReg(SReg).addReg(ShiftReg);
9024 unsigned ValueSReg = RegInfo.createVirtualRegister(RC);
9025 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
9027 ValueReg = ValueSReg;
9030 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9031 .addReg(CmpReg).addReg(ValueReg);
9032 BuildMI(BB, dl, TII->get(PPC::BCC))
9033 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9034 BB->addSuccessor(loop2MBB);
9035 BB->addSuccessor(exitMBB);
9038 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
9039 .addReg(Tmp3Reg).addReg(Tmp2Reg);
9040 BuildMI(BB, dl, TII->get(PPC::STWCX))
9041 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
9042 BuildMI(BB, dl, TII->get(PPC::BCC))
9043 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9044 BB->addSuccessor(loopMBB);
9045 BB->addSuccessor(exitMBB);
9050 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
9055 llvm::MachineBasicBlock *
9056 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
9057 MachineBasicBlock *MBB) const {
9058 DebugLoc DL = MI.getDebugLoc();
9059 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9060 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
9062 MachineFunction *MF = MBB->getParent();
9063 MachineRegisterInfo &MRI = MF->getRegInfo();
9065 const BasicBlock *BB = MBB->getBasicBlock();
9066 MachineFunction::iterator I = ++MBB->getIterator();
9069 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9070 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9072 unsigned DstReg = MI.getOperand(0).getReg();
9073 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
9074 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
9075 unsigned mainDstReg = MRI.createVirtualRegister(RC);
9076 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
9078 MVT PVT = getPointerTy(MF->getDataLayout());
9079 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9080 "Invalid Pointer Size!");
9081 // For v = setjmp(buf), we generate
9084 // SjLjSetup mainMBB
9090 // buf[LabelOffset] = LR
9094 // v = phi(main, restore)
9097 MachineBasicBlock *thisMBB = MBB;
9098 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
9099 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
9100 MF->insert(I, mainMBB);
9101 MF->insert(I, sinkMBB);
9103 MachineInstrBuilder MIB;
9105 // Transfer the remainder of BB and its successor edges to sinkMBB.
9106 sinkMBB->splice(sinkMBB->begin(), MBB,
9107 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9108 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
9110 // Note that the structure of the jmp_buf used here is not compatible
9111 // with that used by libc, and is not designed to be. Specifically, it
9112 // stores only those 'reserved' registers that LLVM does not otherwise
9113 // understand how to spill. Also, by convention, by the time this
9114 // intrinsic is called, Clang has already stored the frame address in the
9115 // first slot of the buffer and stack address in the third. Following the
9116 // X86 target code, we'll store the jump address in the second slot. We also
9117 // need to save the TOC pointer (R2) to handle jumps between shared
9118 // libraries, and that will be stored in the fourth slot. The thread
9119 // identifier (R13) is not affected.
9122 const int64_t LabelOffset = 1 * PVT.getStoreSize();
9123 const int64_t TOCOffset = 3 * PVT.getStoreSize();
9124 const int64_t BPOffset = 4 * PVT.getStoreSize();
9126 // Prepare IP either in reg.
9127 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
9128 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
9129 unsigned BufReg = MI.getOperand(1).getReg();
9131 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
9132 setUsesTOCBasePtr(*MBB->getParent());
9133 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
9137 MIB.setMemRefs(MMOBegin, MMOEnd);
9140 // Naked functions never have a base pointer, and so we use r1. For all
9141 // other functions, this decision must be delayed until during PEI.
9143 if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
9144 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
9146 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
9148 MIB = BuildMI(*thisMBB, MI, DL,
9149 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
9153 MIB.setMemRefs(MMOBegin, MMOEnd);
9156 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
9157 MIB.addRegMask(TRI->getNoPreservedMask());
9159 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
9161 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
9163 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
9165 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
9166 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
9171 BuildMI(mainMBB, DL,
9172 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
9175 if (Subtarget.isPPC64()) {
9176 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
9178 .addImm(LabelOffset)
9181 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
9183 .addImm(LabelOffset)
9187 MIB.setMemRefs(MMOBegin, MMOEnd);
9189 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
9190 mainMBB->addSuccessor(sinkMBB);
9193 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9194 TII->get(PPC::PHI), DstReg)
9195 .addReg(mainDstReg).addMBB(mainMBB)
9196 .addReg(restoreDstReg).addMBB(thisMBB);
9198 MI.eraseFromParent();
9203 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
9204 MachineBasicBlock *MBB) const {
9205 DebugLoc DL = MI.getDebugLoc();
9206 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9208 MachineFunction *MF = MBB->getParent();
9209 MachineRegisterInfo &MRI = MF->getRegInfo();
9212 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9213 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9215 MVT PVT = getPointerTy(MF->getDataLayout());
9216 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9217 "Invalid Pointer Size!");
9219 const TargetRegisterClass *RC =
9220 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
9221 unsigned Tmp = MRI.createVirtualRegister(RC);
9222 // Since FP is only updated here but NOT referenced, it's treated as GPR.
9223 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
9224 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
9228 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
9231 MachineInstrBuilder MIB;
9233 const int64_t LabelOffset = 1 * PVT.getStoreSize();
9234 const int64_t SPOffset = 2 * PVT.getStoreSize();
9235 const int64_t TOCOffset = 3 * PVT.getStoreSize();
9236 const int64_t BPOffset = 4 * PVT.getStoreSize();
9238 unsigned BufReg = MI.getOperand(0).getReg();
9240 // Reload FP (the jumped-to function may not have had a
9241 // frame pointer, and if so, then its r31 will be restored
9243 if (PVT == MVT::i64) {
9244 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
9248 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
9252 MIB.setMemRefs(MMOBegin, MMOEnd);
9255 if (PVT == MVT::i64) {
9256 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
9257 .addImm(LabelOffset)
9260 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
9261 .addImm(LabelOffset)
9264 MIB.setMemRefs(MMOBegin, MMOEnd);
9267 if (PVT == MVT::i64) {
9268 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
9272 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
9276 MIB.setMemRefs(MMOBegin, MMOEnd);
9279 if (PVT == MVT::i64) {
9280 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
9284 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
9288 MIB.setMemRefs(MMOBegin, MMOEnd);
9291 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
9292 setUsesTOCBasePtr(*MBB->getParent());
9293 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
9297 MIB.setMemRefs(MMOBegin, MMOEnd);
9301 BuildMI(*MBB, MI, DL,
9302 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
9303 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
9305 MI.eraseFromParent();
9310 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9311 MachineBasicBlock *BB) const {
9312 if (MI.getOpcode() == TargetOpcode::STACKMAP ||
9313 MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9314 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
9315 MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9316 // Call lowering should have added an r2 operand to indicate a dependence
9317 // on the TOC base pointer value. It can't however, because there is no
9318 // way to mark the dependence as implicit there, and so the stackmap code
9319 // will confuse it with a regular operand. Instead, add the dependence
9321 setUsesTOCBasePtr(*BB->getParent());
9322 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
9325 return emitPatchPoint(MI, BB);
9328 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
9329 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
9330 return emitEHSjLjSetJmp(MI, BB);
9331 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
9332 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
9333 return emitEHSjLjLongJmp(MI, BB);
9336 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9338 // To "insert" these instructions we actually have to insert their
9339 // control-flow patterns.
9340 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9341 MachineFunction::iterator It = ++BB->getIterator();
9343 MachineFunction *F = BB->getParent();
9345 if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9346 MI.getOpcode() == PPC::SELECT_CC_I8 ||
9347 MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) {
9348 SmallVector<MachineOperand, 2> Cond;
9349 if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9350 MI.getOpcode() == PPC::SELECT_CC_I8)
9351 Cond.push_back(MI.getOperand(4));
9353 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
9354 Cond.push_back(MI.getOperand(1));
9356 DebugLoc dl = MI.getDebugLoc();
9357 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
9358 MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
9359 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9360 MI.getOpcode() == PPC::SELECT_CC_I8 ||
9361 MI.getOpcode() == PPC::SELECT_CC_F4 ||
9362 MI.getOpcode() == PPC::SELECT_CC_F8 ||
9363 MI.getOpcode() == PPC::SELECT_CC_QFRC ||
9364 MI.getOpcode() == PPC::SELECT_CC_QSRC ||
9365 MI.getOpcode() == PPC::SELECT_CC_QBRC ||
9366 MI.getOpcode() == PPC::SELECT_CC_VRRC ||
9367 MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
9368 MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
9369 MI.getOpcode() == PPC::SELECT_CC_VSRC ||
9370 MI.getOpcode() == PPC::SELECT_I4 ||
9371 MI.getOpcode() == PPC::SELECT_I8 ||
9372 MI.getOpcode() == PPC::SELECT_F4 ||
9373 MI.getOpcode() == PPC::SELECT_F8 ||
9374 MI.getOpcode() == PPC::SELECT_QFRC ||
9375 MI.getOpcode() == PPC::SELECT_QSRC ||
9376 MI.getOpcode() == PPC::SELECT_QBRC ||
9377 MI.getOpcode() == PPC::SELECT_VRRC ||
9378 MI.getOpcode() == PPC::SELECT_VSFRC ||
9379 MI.getOpcode() == PPC::SELECT_VSSRC ||
9380 MI.getOpcode() == PPC::SELECT_VSRC) {
9381 // The incoming instruction knows the destination vreg to set, the
9382 // condition code register to branch on, the true/false values to
9383 // select between, and a branch opcode to use.
9388 // cmpTY ccX, r1, r2
9390 // fallthrough --> copy0MBB
9391 MachineBasicBlock *thisMBB = BB;
9392 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9393 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9394 DebugLoc dl = MI.getDebugLoc();
9395 F->insert(It, copy0MBB);
9396 F->insert(It, sinkMBB);
9398 // Transfer the remainder of BB and its successor edges to sinkMBB.
9399 sinkMBB->splice(sinkMBB->begin(), BB,
9400 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9401 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9403 // Next, add the true and fallthrough blocks as its successors.
9404 BB->addSuccessor(copy0MBB);
9405 BB->addSuccessor(sinkMBB);
9407 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
9408 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
9409 MI.getOpcode() == PPC::SELECT_QFRC ||
9410 MI.getOpcode() == PPC::SELECT_QSRC ||
9411 MI.getOpcode() == PPC::SELECT_QBRC ||
9412 MI.getOpcode() == PPC::SELECT_VRRC ||
9413 MI.getOpcode() == PPC::SELECT_VSFRC ||
9414 MI.getOpcode() == PPC::SELECT_VSSRC ||
9415 MI.getOpcode() == PPC::SELECT_VSRC) {
9416 BuildMI(BB, dl, TII->get(PPC::BC))
9417 .addReg(MI.getOperand(1).getReg())
9420 unsigned SelectPred = MI.getOperand(4).getImm();
9421 BuildMI(BB, dl, TII->get(PPC::BCC))
9423 .addReg(MI.getOperand(1).getReg())
9428 // %FalseValue = ...
9429 // # fallthrough to sinkMBB
9432 // Update machine-CFG edges
9433 BB->addSuccessor(sinkMBB);
9436 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9439 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
9440 .addReg(MI.getOperand(3).getReg())
9442 .addReg(MI.getOperand(2).getReg())
9444 } else if (MI.getOpcode() == PPC::ReadTB) {
9445 // To read the 64-bit time-base register on a 32-bit target, we read the
9446 // two halves. Should the counter have wrapped while it was being read, we
9447 // need to try again.
9450 // mfspr Rx,TBU # load from TBU
9451 // mfspr Ry,TB # load from TB
9452 // mfspr Rz,TBU # load from TBU
9453 // cmpw crX,Rx,Rz # check if 'old'='new'
9454 // bne readLoop # branch if they're not equal
9457 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
9458 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9459 DebugLoc dl = MI.getDebugLoc();
9460 F->insert(It, readMBB);
9461 F->insert(It, sinkMBB);
9463 // Transfer the remainder of BB and its successor edges to sinkMBB.
9464 sinkMBB->splice(sinkMBB->begin(), BB,
9465 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9466 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9468 BB->addSuccessor(readMBB);
9471 MachineRegisterInfo &RegInfo = F->getRegInfo();
9472 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9473 unsigned LoReg = MI.getOperand(0).getReg();
9474 unsigned HiReg = MI.getOperand(1).getReg();
9476 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
9477 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
9478 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
9480 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9482 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
9483 .addReg(HiReg).addReg(ReadAgainReg);
9484 BuildMI(BB, dl, TII->get(PPC::BCC))
9485 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
9487 BB->addSuccessor(readMBB);
9488 BB->addSuccessor(sinkMBB);
9489 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
9490 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
9491 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
9492 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
9493 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
9494 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
9495 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
9496 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
9498 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
9499 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
9500 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
9501 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
9502 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
9503 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
9504 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
9505 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
9507 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
9508 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
9509 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
9510 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
9511 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
9512 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
9513 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
9514 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
9516 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
9517 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
9518 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
9519 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
9520 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
9521 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
9522 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
9523 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
9525 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
9526 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
9527 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
9528 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
9529 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
9530 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
9531 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
9532 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
9534 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
9535 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
9536 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
9537 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
9538 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
9539 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
9540 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
9541 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
9543 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
9544 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
9545 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
9546 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
9547 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
9548 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
9549 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
9550 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
9552 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
9553 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
9554 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
9555 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
9556 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
9557 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
9558 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
9559 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
9561 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
9562 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
9563 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
9564 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
9565 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
9566 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
9567 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
9568 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
9570 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
9571 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
9572 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
9573 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
9574 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
9575 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
9576 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
9577 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
9579 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
9580 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
9581 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
9582 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
9583 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
9584 BB = EmitAtomicBinary(MI, BB, 4, 0);
9585 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
9586 BB = EmitAtomicBinary(MI, BB, 8, 0);
9587 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
9588 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
9589 (Subtarget.hasPartwordAtomics() &&
9590 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
9591 (Subtarget.hasPartwordAtomics() &&
9592 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
9593 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
9595 auto LoadMnemonic = PPC::LDARX;
9596 auto StoreMnemonic = PPC::STDCX;
9597 switch (MI.getOpcode()) {
9599 llvm_unreachable("Compare and swap of unknown size");
9600 case PPC::ATOMIC_CMP_SWAP_I8:
9601 LoadMnemonic = PPC::LBARX;
9602 StoreMnemonic = PPC::STBCX;
9603 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9605 case PPC::ATOMIC_CMP_SWAP_I16:
9606 LoadMnemonic = PPC::LHARX;
9607 StoreMnemonic = PPC::STHCX;
9608 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9610 case PPC::ATOMIC_CMP_SWAP_I32:
9611 LoadMnemonic = PPC::LWARX;
9612 StoreMnemonic = PPC::STWCX;
9614 case PPC::ATOMIC_CMP_SWAP_I64:
9615 LoadMnemonic = PPC::LDARX;
9616 StoreMnemonic = PPC::STDCX;
9619 unsigned dest = MI.getOperand(0).getReg();
9620 unsigned ptrA = MI.getOperand(1).getReg();
9621 unsigned ptrB = MI.getOperand(2).getReg();
9622 unsigned oldval = MI.getOperand(3).getReg();
9623 unsigned newval = MI.getOperand(4).getReg();
9624 DebugLoc dl = MI.getDebugLoc();
9626 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9627 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9628 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9629 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9630 F->insert(It, loop1MBB);
9631 F->insert(It, loop2MBB);
9632 F->insert(It, midMBB);
9633 F->insert(It, exitMBB);
9634 exitMBB->splice(exitMBB->begin(), BB,
9635 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9636 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9640 // fallthrough --> loopMBB
9641 BB->addSuccessor(loop1MBB);
9644 // l[bhwd]arx dest, ptr
9645 // cmp[wd] dest, oldval
9648 // st[bhwd]cx. newval, ptr
9652 // st[bhwd]cx. dest, ptr
9655 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9656 .addReg(ptrA).addReg(ptrB);
9657 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
9658 .addReg(oldval).addReg(dest);
9659 BuildMI(BB, dl, TII->get(PPC::BCC))
9660 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9661 BB->addSuccessor(loop2MBB);
9662 BB->addSuccessor(midMBB);
9665 BuildMI(BB, dl, TII->get(StoreMnemonic))
9666 .addReg(newval).addReg(ptrA).addReg(ptrB);
9667 BuildMI(BB, dl, TII->get(PPC::BCC))
9668 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9669 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9670 BB->addSuccessor(loop1MBB);
9671 BB->addSuccessor(exitMBB);
9674 BuildMI(BB, dl, TII->get(StoreMnemonic))
9675 .addReg(dest).addReg(ptrA).addReg(ptrB);
9676 BB->addSuccessor(exitMBB);
9681 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
9682 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
9683 // We must use 64-bit registers for addresses when targeting 64-bit,
9684 // since we're actually doing arithmetic on them. Other registers
9686 bool is64bit = Subtarget.isPPC64();
9687 bool isLittleEndian = Subtarget.isLittleEndian();
9688 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
9690 unsigned dest = MI.getOperand(0).getReg();
9691 unsigned ptrA = MI.getOperand(1).getReg();
9692 unsigned ptrB = MI.getOperand(2).getReg();
9693 unsigned oldval = MI.getOperand(3).getReg();
9694 unsigned newval = MI.getOperand(4).getReg();
9695 DebugLoc dl = MI.getDebugLoc();
9697 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9698 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9699 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9700 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9701 F->insert(It, loop1MBB);
9702 F->insert(It, loop2MBB);
9703 F->insert(It, midMBB);
9704 F->insert(It, exitMBB);
9705 exitMBB->splice(exitMBB->begin(), BB,
9706 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9707 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9709 MachineRegisterInfo &RegInfo = F->getRegInfo();
9710 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9711 : &PPC::GPRCRegClass;
9712 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9713 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9715 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
9716 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
9717 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
9718 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
9719 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
9720 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9721 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9722 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9723 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9724 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9725 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9727 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
9728 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9731 // fallthrough --> loopMBB
9732 BB->addSuccessor(loop1MBB);
9734 // The 4-byte load must be aligned, while a char or short may be
9735 // anywhere in the word. Hence all this nasty bookkeeping code.
9736 // add ptr1, ptrA, ptrB [copy if ptrA==0]
9737 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9738 // xori shift, shift1, 24 [16]
9739 // rlwinm ptr, ptr1, 0, 0, 29
9740 // slw newval2, newval, shift
9741 // slw oldval2, oldval,shift
9742 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9743 // slw mask, mask2, shift
9744 // and newval3, newval2, mask
9745 // and oldval3, oldval2, mask
9747 // lwarx tmpDest, ptr
9748 // and tmp, tmpDest, mask
9749 // cmpw tmp, oldval3
9752 // andc tmp2, tmpDest, mask
9753 // or tmp4, tmp2, newval3
9758 // stwcx. tmpDest, ptr
9760 // srw dest, tmpDest, shift
9761 if (ptrA != ZeroReg) {
9762 Ptr1Reg = RegInfo.createVirtualRegister(RC);
9763 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9764 .addReg(ptrA).addReg(ptrB);
9768 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9769 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9770 if (!isLittleEndian)
9771 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9772 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9774 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9775 .addReg(Ptr1Reg).addImm(0).addImm(61);
9777 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9778 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9779 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
9780 .addReg(newval).addReg(ShiftReg);
9781 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
9782 .addReg(oldval).addReg(ShiftReg);
9784 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9786 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9787 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
9788 .addReg(Mask3Reg).addImm(65535);
9790 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9791 .addReg(Mask2Reg).addReg(ShiftReg);
9792 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
9793 .addReg(NewVal2Reg).addReg(MaskReg);
9794 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
9795 .addReg(OldVal2Reg).addReg(MaskReg);
9798 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9799 .addReg(ZeroReg).addReg(PtrReg);
9800 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
9801 .addReg(TmpDestReg).addReg(MaskReg);
9802 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
9803 .addReg(TmpReg).addReg(OldVal3Reg);
9804 BuildMI(BB, dl, TII->get(PPC::BCC))
9805 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9806 BB->addSuccessor(loop2MBB);
9807 BB->addSuccessor(midMBB);
9810 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
9811 .addReg(TmpDestReg).addReg(MaskReg);
9812 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
9813 .addReg(Tmp2Reg).addReg(NewVal3Reg);
9814 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
9815 .addReg(ZeroReg).addReg(PtrReg);
9816 BuildMI(BB, dl, TII->get(PPC::BCC))
9817 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9818 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9819 BB->addSuccessor(loop1MBB);
9820 BB->addSuccessor(exitMBB);
9823 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
9824 .addReg(ZeroReg).addReg(PtrReg);
9825 BB->addSuccessor(exitMBB);
9830 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
9832 } else if (MI.getOpcode() == PPC::FADDrtz) {
9833 // This pseudo performs an FADD with rounding mode temporarily forced
9834 // to round-to-zero. We emit this via custom inserter since the FPSCR
9835 // is not modeled at the SelectionDAG level.
9836 unsigned Dest = MI.getOperand(0).getReg();
9837 unsigned Src1 = MI.getOperand(1).getReg();
9838 unsigned Src2 = MI.getOperand(2).getReg();
9839 DebugLoc dl = MI.getDebugLoc();
9841 MachineRegisterInfo &RegInfo = F->getRegInfo();
9842 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
9844 // Save FPSCR value.
9845 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
9847 // Set rounding mode to round-to-zero.
9848 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
9849 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
9851 // Perform addition.
9852 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
9854 // Restore FPSCR value.
9855 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
9856 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9857 MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
9858 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9859 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
9860 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9861 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
9864 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9865 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
9867 MachineRegisterInfo &RegInfo = F->getRegInfo();
9868 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
9869 &PPC::GPRCRegClass :
9870 &PPC::G8RCRegClass);
9872 DebugLoc dl = MI.getDebugLoc();
9873 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
9874 .addReg(MI.getOperand(1).getReg())
9876 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
9877 MI.getOperand(0).getReg())
9878 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
9879 } else if (MI.getOpcode() == PPC::TCHECK_RET) {
9880 DebugLoc Dl = MI.getDebugLoc();
9881 MachineRegisterInfo &RegInfo = F->getRegInfo();
9882 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9883 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
9886 llvm_unreachable("Unexpected instr type to insert");
9889 MI.eraseFromParent(); // The pseudo instruction is gone now.
9893 //===----------------------------------------------------------------------===//
9894 // Target Optimization Hooks
9895 //===----------------------------------------------------------------------===//
9897 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
9898 // For the estimates, convergence is quadratic, so we essentially double the
9899 // number of digits correct after every iteration. For both FRE and FRSQRTE,
9900 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
9901 // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
9902 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
9903 if (VT.getScalarType() == MVT::f64)
9905 return RefinementSteps;
9908 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
9909 int Enabled, int &RefinementSteps,
9910 bool &UseOneConstNR,
9911 bool Reciprocal) const {
9912 EVT VT = Operand.getValueType();
9913 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
9914 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
9915 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9916 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9917 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9918 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9919 if (RefinementSteps == ReciprocalEstimate::Unspecified)
9920 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
9922 UseOneConstNR = true;
9923 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
9928 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
9930 int &RefinementSteps) const {
9931 EVT VT = Operand.getValueType();
9932 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
9933 (VT == MVT::f64 && Subtarget.hasFRE()) ||
9934 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9935 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9936 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9937 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9938 if (RefinementSteps == ReciprocalEstimate::Unspecified)
9939 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
9940 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
9945 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
9946 // Note: This functionality is used only when unsafe-fp-math is enabled, and
9947 // on cores with reciprocal estimates (which are used when unsafe-fp-math is
9948 // enabled for division), this functionality is redundant with the default
9949 // combiner logic (once the division -> reciprocal/multiply transformation
9950 // has taken place). As a result, this matters more for older cores than for
9953 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9954 // reciprocal if there are two or more FDIVs (for embedded cores with only
9955 // one FP pipeline) for three or more FDIVs (for generic OOO cores).
9956 switch (Subtarget.getDarwinDirective()) {
9961 case PPC::DIR_E500mc:
9962 case PPC::DIR_E5500:
9967 // isConsecutiveLSLoc needs to work even if all adds have not yet been
9968 // collapsed, and so we need to look through chains of them.
9969 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
9970 int64_t& Offset, SelectionDAG &DAG) {
9971 if (DAG.isBaseWithConstantOffset(Loc)) {
9972 Base = Loc.getOperand(0);
9973 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
9975 // The base might itself be a base plus an offset, and if so, accumulate
9977 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
9981 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
9982 unsigned Bytes, int Dist,
9983 SelectionDAG &DAG) {
9984 if (VT.getSizeInBits() / 8 != Bytes)
9987 SDValue BaseLoc = Base->getBasePtr();
9988 if (Loc.getOpcode() == ISD::FrameIndex) {
9989 if (BaseLoc.getOpcode() != ISD::FrameIndex)
9991 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9992 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
9993 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
9994 int FS = MFI.getObjectSize(FI);
9995 int BFS = MFI.getObjectSize(BFI);
9996 if (FS != BFS || FS != (int)Bytes) return false;
9997 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
10000 SDValue Base1 = Loc, Base2 = BaseLoc;
10001 int64_t Offset1 = 0, Offset2 = 0;
10002 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
10003 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
10004 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
10007 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10008 const GlobalValue *GV1 = nullptr;
10009 const GlobalValue *GV2 = nullptr;
10012 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
10013 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
10014 if (isGA1 && isGA2 && GV1 == GV2)
10015 return Offset1 == (Offset2 + Dist*Bytes);
10019 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
10020 // not enforce equality of the chain operands.
10021 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
10022 unsigned Bytes, int Dist,
10023 SelectionDAG &DAG) {
10024 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
10025 EVT VT = LS->getMemoryVT();
10026 SDValue Loc = LS->getBasePtr();
10027 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
10030 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
10032 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10033 default: return false;
10034 case Intrinsic::ppc_qpx_qvlfd:
10035 case Intrinsic::ppc_qpx_qvlfda:
10038 case Intrinsic::ppc_qpx_qvlfs:
10039 case Intrinsic::ppc_qpx_qvlfsa:
10042 case Intrinsic::ppc_qpx_qvlfcd:
10043 case Intrinsic::ppc_qpx_qvlfcda:
10046 case Intrinsic::ppc_qpx_qvlfcs:
10047 case Intrinsic::ppc_qpx_qvlfcsa:
10050 case Intrinsic::ppc_qpx_qvlfiwa:
10051 case Intrinsic::ppc_qpx_qvlfiwz:
10052 case Intrinsic::ppc_altivec_lvx:
10053 case Intrinsic::ppc_altivec_lvxl:
10054 case Intrinsic::ppc_vsx_lxvw4x:
10055 case Intrinsic::ppc_vsx_lxvw4x_be:
10058 case Intrinsic::ppc_vsx_lxvd2x:
10059 case Intrinsic::ppc_vsx_lxvd2x_be:
10062 case Intrinsic::ppc_altivec_lvebx:
10065 case Intrinsic::ppc_altivec_lvehx:
10068 case Intrinsic::ppc_altivec_lvewx:
10073 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
10076 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
10078 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10079 default: return false;
10080 case Intrinsic::ppc_qpx_qvstfd:
10081 case Intrinsic::ppc_qpx_qvstfda:
10084 case Intrinsic::ppc_qpx_qvstfs:
10085 case Intrinsic::ppc_qpx_qvstfsa:
10088 case Intrinsic::ppc_qpx_qvstfcd:
10089 case Intrinsic::ppc_qpx_qvstfcda:
10092 case Intrinsic::ppc_qpx_qvstfcs:
10093 case Intrinsic::ppc_qpx_qvstfcsa:
10096 case Intrinsic::ppc_qpx_qvstfiw:
10097 case Intrinsic::ppc_qpx_qvstfiwa:
10098 case Intrinsic::ppc_altivec_stvx:
10099 case Intrinsic::ppc_altivec_stvxl:
10100 case Intrinsic::ppc_vsx_stxvw4x:
10103 case Intrinsic::ppc_vsx_stxvd2x:
10106 case Intrinsic::ppc_vsx_stxvw4x_be:
10109 case Intrinsic::ppc_vsx_stxvd2x_be:
10112 case Intrinsic::ppc_altivec_stvebx:
10115 case Intrinsic::ppc_altivec_stvehx:
10118 case Intrinsic::ppc_altivec_stvewx:
10123 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
10129 // Return true is there is a nearyby consecutive load to the one provided
10130 // (regardless of alignment). We search up and down the chain, looking though
10131 // token factors and other loads (but nothing else). As a result, a true result
10132 // indicates that it is safe to create a new consecutive load adjacent to the
10134 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
10135 SDValue Chain = LD->getChain();
10136 EVT VT = LD->getMemoryVT();
10138 SmallSet<SDNode *, 16> LoadRoots;
10139 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
10140 SmallSet<SDNode *, 16> Visited;
10142 // First, search up the chain, branching to follow all token-factor operands.
10143 // If we find a consecutive load, then we're done, otherwise, record all
10144 // nodes just above the top-level loads and token factors.
10145 while (!Queue.empty()) {
10146 SDNode *ChainNext = Queue.pop_back_val();
10147 if (!Visited.insert(ChainNext).second)
10150 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
10151 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10154 if (!Visited.count(ChainLD->getChain().getNode()))
10155 Queue.push_back(ChainLD->getChain().getNode());
10156 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
10157 for (const SDUse &O : ChainNext->ops())
10158 if (!Visited.count(O.getNode()))
10159 Queue.push_back(O.getNode());
10161 LoadRoots.insert(ChainNext);
10164 // Second, search down the chain, starting from the top-level nodes recorded
10165 // in the first phase. These top-level nodes are the nodes just above all
10166 // loads and token factors. Starting with their uses, recursively look though
10167 // all loads (just the chain uses) and token factors to find a consecutive
10172 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
10173 IE = LoadRoots.end(); I != IE; ++I) {
10174 Queue.push_back(*I);
10176 while (!Queue.empty()) {
10177 SDNode *LoadRoot = Queue.pop_back_val();
10178 if (!Visited.insert(LoadRoot).second)
10181 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
10182 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10185 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
10186 UE = LoadRoot->use_end(); UI != UE; ++UI)
10187 if (((isa<MemSDNode>(*UI) &&
10188 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
10189 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
10190 Queue.push_back(*UI);
10197 /// This function is called when we have proved that a SETCC node can be replaced
10198 /// by subtraction (and other supporting instructions) so that the result of
10199 /// comparison is kept in a GPR instead of CR. This function is purely for
10200 /// codegen purposes and has some flags to guide the codegen process.
10201 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
10202 bool Swap, SDLoc &DL, SelectionDAG &DAG) {
10203 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10205 // Zero extend the operands to the largest legal integer. Originally, they
10206 // must be of a strictly smaller size.
10207 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
10208 DAG.getConstant(Size, DL, MVT::i32));
10209 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
10210 DAG.getConstant(Size, DL, MVT::i32));
10212 // Swap if needed. Depends on the condition code.
10214 std::swap(Op0, Op1);
10216 // Subtract extended integers.
10217 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
10219 // Move the sign bit to the least significant position and zero out the rest.
10220 // Now the least significant bit carries the result of original comparison.
10221 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
10222 DAG.getConstant(Size - 1, DL, MVT::i32));
10223 auto Final = Shifted;
10225 // Complement the result if needed. Based on the condition code.
10227 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
10228 DAG.getConstant(1, DL, MVT::i64));
10230 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
10233 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
10234 DAGCombinerInfo &DCI) const {
10235 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10237 SelectionDAG &DAG = DCI.DAG;
10240 // Size of integers being compared has a critical role in the following
10241 // analysis, so we prefer to do this when all types are legal.
10242 if (!DCI.isAfterLegalizeVectorOps())
10245 // If all users of SETCC extend its value to a legal integer type
10246 // then we replace SETCC with a subtraction
10247 for (SDNode::use_iterator UI = N->use_begin(),
10248 UE = N->use_end(); UI != UE; ++UI) {
10249 if (UI->getOpcode() != ISD::ZERO_EXTEND)
10253 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10254 auto OpSize = N->getOperand(0).getValueSizeInBits();
10256 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
10258 if (OpSize < Size) {
10262 return generateEquivalentSub(N, Size, false, false, DL, DAG);
10264 return generateEquivalentSub(N, Size, true, true, DL, DAG);
10266 return generateEquivalentSub(N, Size, false, true, DL, DAG);
10268 return generateEquivalentSub(N, Size, true, false, DL, DAG);
10275 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
10276 DAGCombinerInfo &DCI) const {
10277 SelectionDAG &DAG = DCI.DAG;
10280 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
10281 // If we're tracking CR bits, we need to be careful that we don't have:
10282 // trunc(binary-ops(zext(x), zext(y)))
10284 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
10285 // such that we're unnecessarily moving things into GPRs when it would be
10286 // better to keep them in CR bits.
10288 // Note that trunc here can be an actual i1 trunc, or can be the effective
10289 // truncation that comes from a setcc or select_cc.
10290 if (N->getOpcode() == ISD::TRUNCATE &&
10291 N->getValueType(0) != MVT::i1)
10294 if (N->getOperand(0).getValueType() != MVT::i32 &&
10295 N->getOperand(0).getValueType() != MVT::i64)
10298 if (N->getOpcode() == ISD::SETCC ||
10299 N->getOpcode() == ISD::SELECT_CC) {
10300 // If we're looking at a comparison, then we need to make sure that the
10301 // high bits (all except for the first) don't matter the result.
10303 cast<CondCodeSDNode>(N->getOperand(
10304 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
10305 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
10307 if (ISD::isSignedIntSetCC(CC)) {
10308 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
10309 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
10311 } else if (ISD::isUnsignedIntSetCC(CC)) {
10312 if (!DAG.MaskedValueIsZero(N->getOperand(0),
10313 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
10314 !DAG.MaskedValueIsZero(N->getOperand(1),
10315 APInt::getHighBitsSet(OpBits, OpBits-1)))
10316 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
10319 // This is neither a signed nor an unsigned comparison, just make sure
10320 // that the high bits are equal.
10321 APInt Op1Zero, Op1One;
10322 APInt Op2Zero, Op2One;
10323 DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
10324 DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
10326 // We don't really care about what is known about the first bit (if
10327 // anything), so clear it in all masks prior to comparing them.
10328 Op1Zero.clearBit(0); Op1One.clearBit(0);
10329 Op2Zero.clearBit(0); Op2One.clearBit(0);
10331 if (Op1Zero != Op2Zero || Op1One != Op2One)
10336 // We now know that the higher-order bits are irrelevant, we just need to
10337 // make sure that all of the intermediate operations are bit operations, and
10338 // all inputs are extensions.
10339 if (N->getOperand(0).getOpcode() != ISD::AND &&
10340 N->getOperand(0).getOpcode() != ISD::OR &&
10341 N->getOperand(0).getOpcode() != ISD::XOR &&
10342 N->getOperand(0).getOpcode() != ISD::SELECT &&
10343 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
10344 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
10345 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
10346 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
10347 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
10350 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
10351 N->getOperand(1).getOpcode() != ISD::AND &&
10352 N->getOperand(1).getOpcode() != ISD::OR &&
10353 N->getOperand(1).getOpcode() != ISD::XOR &&
10354 N->getOperand(1).getOpcode() != ISD::SELECT &&
10355 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
10356 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
10357 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
10358 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
10359 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
10362 SmallVector<SDValue, 4> Inputs;
10363 SmallVector<SDValue, 8> BinOps, PromOps;
10364 SmallPtrSet<SDNode *, 16> Visited;
10366 for (unsigned i = 0; i < 2; ++i) {
10367 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10368 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10369 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10370 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10371 isa<ConstantSDNode>(N->getOperand(i)))
10372 Inputs.push_back(N->getOperand(i));
10374 BinOps.push_back(N->getOperand(i));
10376 if (N->getOpcode() == ISD::TRUNCATE)
10380 // Visit all inputs, collect all binary operations (and, or, xor and
10381 // select) that are all fed by extensions.
10382 while (!BinOps.empty()) {
10383 SDValue BinOp = BinOps.back();
10386 if (!Visited.insert(BinOp.getNode()).second)
10389 PromOps.push_back(BinOp);
10391 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10392 // The condition of the select is not promoted.
10393 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10395 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10398 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10399 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10400 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10401 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10402 isa<ConstantSDNode>(BinOp.getOperand(i))) {
10403 Inputs.push_back(BinOp.getOperand(i));
10404 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10405 BinOp.getOperand(i).getOpcode() == ISD::OR ||
10406 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10407 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10408 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
10409 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10410 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10411 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10412 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
10413 BinOps.push_back(BinOp.getOperand(i));
10415 // We have an input that is not an extension or another binary
10416 // operation; we'll abort this transformation.
10422 // Make sure that this is a self-contained cluster of operations (which
10423 // is not quite the same thing as saying that everything has only one
10425 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10426 if (isa<ConstantSDNode>(Inputs[i]))
10429 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10430 UE = Inputs[i].getNode()->use_end();
10432 SDNode *User = *UI;
10433 if (User != N && !Visited.count(User))
10436 // Make sure that we're not going to promote the non-output-value
10437 // operand(s) or SELECT or SELECT_CC.
10438 // FIXME: Although we could sometimes handle this, and it does occur in
10439 // practice that one of the condition inputs to the select is also one of
10440 // the outputs, we currently can't deal with this.
10441 if (User->getOpcode() == ISD::SELECT) {
10442 if (User->getOperand(0) == Inputs[i])
10444 } else if (User->getOpcode() == ISD::SELECT_CC) {
10445 if (User->getOperand(0) == Inputs[i] ||
10446 User->getOperand(1) == Inputs[i])
10452 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10453 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10454 UE = PromOps[i].getNode()->use_end();
10456 SDNode *User = *UI;
10457 if (User != N && !Visited.count(User))
10460 // Make sure that we're not going to promote the non-output-value
10461 // operand(s) or SELECT or SELECT_CC.
10462 // FIXME: Although we could sometimes handle this, and it does occur in
10463 // practice that one of the condition inputs to the select is also one of
10464 // the outputs, we currently can't deal with this.
10465 if (User->getOpcode() == ISD::SELECT) {
10466 if (User->getOperand(0) == PromOps[i])
10468 } else if (User->getOpcode() == ISD::SELECT_CC) {
10469 if (User->getOperand(0) == PromOps[i] ||
10470 User->getOperand(1) == PromOps[i])
10476 // Replace all inputs with the extension operand.
10477 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10478 // Constants may have users outside the cluster of to-be-promoted nodes,
10479 // and so we need to replace those as we do the promotions.
10480 if (isa<ConstantSDNode>(Inputs[i]))
10483 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
10486 std::list<HandleSDNode> PromOpHandles;
10487 for (auto &PromOp : PromOps)
10488 PromOpHandles.emplace_back(PromOp);
10490 // Replace all operations (these are all the same, but have a different
10491 // (i1) return type). DAG.getNode will validate that the types of
10492 // a binary operator match, so go through the list in reverse so that
10493 // we've likely promoted both operands first. Any intermediate truncations or
10494 // extensions disappear.
10495 while (!PromOpHandles.empty()) {
10496 SDValue PromOp = PromOpHandles.back().getValue();
10497 PromOpHandles.pop_back();
10499 if (PromOp.getOpcode() == ISD::TRUNCATE ||
10500 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
10501 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
10502 PromOp.getOpcode() == ISD::ANY_EXTEND) {
10503 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
10504 PromOp.getOperand(0).getValueType() != MVT::i1) {
10505 // The operand is not yet ready (see comment below).
10506 PromOpHandles.emplace_front(PromOp);
10510 SDValue RepValue = PromOp.getOperand(0);
10511 if (isa<ConstantSDNode>(RepValue))
10512 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
10514 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
10519 switch (PromOp.getOpcode()) {
10520 default: C = 0; break;
10521 case ISD::SELECT: C = 1; break;
10522 case ISD::SELECT_CC: C = 2; break;
10525 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10526 PromOp.getOperand(C).getValueType() != MVT::i1) ||
10527 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10528 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
10529 // The to-be-promoted operands of this node have not yet been
10530 // promoted (this should be rare because we're going through the
10531 // list backward, but if one of the operands has several users in
10532 // this cluster of to-be-promoted nodes, it is possible).
10533 PromOpHandles.emplace_front(PromOp);
10537 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10538 PromOp.getNode()->op_end());
10540 // If there are any constant inputs, make sure they're replaced now.
10541 for (unsigned i = 0; i < 2; ++i)
10542 if (isa<ConstantSDNode>(Ops[C+i]))
10543 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
10545 DAG.ReplaceAllUsesOfValueWith(PromOp,
10546 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
10549 // Now we're left with the initial truncation itself.
10550 if (N->getOpcode() == ISD::TRUNCATE)
10551 return N->getOperand(0);
10553 // Otherwise, this is a comparison. The operands to be compared have just
10554 // changed type (to i1), but everything else is the same.
10555 return SDValue(N, 0);
10558 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
10559 DAGCombinerInfo &DCI) const {
10560 SelectionDAG &DAG = DCI.DAG;
10563 // If we're tracking CR bits, we need to be careful that we don't have:
10564 // zext(binary-ops(trunc(x), trunc(y)))
10566 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
10567 // such that we're unnecessarily moving things into CR bits that can more
10568 // efficiently stay in GPRs. Note that if we're not certain that the high
10569 // bits are set as required by the final extension, we still may need to do
10570 // some masking to get the proper behavior.
10572 // This same functionality is important on PPC64 when dealing with
10573 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
10574 // the return values of functions. Because it is so similar, it is handled
10577 if (N->getValueType(0) != MVT::i32 &&
10578 N->getValueType(0) != MVT::i64)
10581 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
10582 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
10585 if (N->getOperand(0).getOpcode() != ISD::AND &&
10586 N->getOperand(0).getOpcode() != ISD::OR &&
10587 N->getOperand(0).getOpcode() != ISD::XOR &&
10588 N->getOperand(0).getOpcode() != ISD::SELECT &&
10589 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
10592 SmallVector<SDValue, 4> Inputs;
10593 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
10594 SmallPtrSet<SDNode *, 16> Visited;
10596 // Visit all inputs, collect all binary operations (and, or, xor and
10597 // select) that are all fed by truncations.
10598 while (!BinOps.empty()) {
10599 SDValue BinOp = BinOps.back();
10602 if (!Visited.insert(BinOp.getNode()).second)
10605 PromOps.push_back(BinOp);
10607 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10608 // The condition of the select is not promoted.
10609 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10611 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10614 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10615 isa<ConstantSDNode>(BinOp.getOperand(i))) {
10616 Inputs.push_back(BinOp.getOperand(i));
10617 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10618 BinOp.getOperand(i).getOpcode() == ISD::OR ||
10619 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10620 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10621 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
10622 BinOps.push_back(BinOp.getOperand(i));
10624 // We have an input that is not a truncation or another binary
10625 // operation; we'll abort this transformation.
10631 // The operands of a select that must be truncated when the select is
10632 // promoted because the operand is actually part of the to-be-promoted set.
10633 DenseMap<SDNode *, EVT> SelectTruncOp[2];
10635 // Make sure that this is a self-contained cluster of operations (which
10636 // is not quite the same thing as saying that everything has only one
10638 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10639 if (isa<ConstantSDNode>(Inputs[i]))
10642 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10643 UE = Inputs[i].getNode()->use_end();
10645 SDNode *User = *UI;
10646 if (User != N && !Visited.count(User))
10649 // If we're going to promote the non-output-value operand(s) or SELECT or
10650 // SELECT_CC, record them for truncation.
10651 if (User->getOpcode() == ISD::SELECT) {
10652 if (User->getOperand(0) == Inputs[i])
10653 SelectTruncOp[0].insert(std::make_pair(User,
10654 User->getOperand(0).getValueType()));
10655 } else if (User->getOpcode() == ISD::SELECT_CC) {
10656 if (User->getOperand(0) == Inputs[i])
10657 SelectTruncOp[0].insert(std::make_pair(User,
10658 User->getOperand(0).getValueType()));
10659 if (User->getOperand(1) == Inputs[i])
10660 SelectTruncOp[1].insert(std::make_pair(User,
10661 User->getOperand(1).getValueType()));
10666 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10667 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10668 UE = PromOps[i].getNode()->use_end();
10670 SDNode *User = *UI;
10671 if (User != N && !Visited.count(User))
10674 // If we're going to promote the non-output-value operand(s) or SELECT or
10675 // SELECT_CC, record them for truncation.
10676 if (User->getOpcode() == ISD::SELECT) {
10677 if (User->getOperand(0) == PromOps[i])
10678 SelectTruncOp[0].insert(std::make_pair(User,
10679 User->getOperand(0).getValueType()));
10680 } else if (User->getOpcode() == ISD::SELECT_CC) {
10681 if (User->getOperand(0) == PromOps[i])
10682 SelectTruncOp[0].insert(std::make_pair(User,
10683 User->getOperand(0).getValueType()));
10684 if (User->getOperand(1) == PromOps[i])
10685 SelectTruncOp[1].insert(std::make_pair(User,
10686 User->getOperand(1).getValueType()));
10691 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
10692 bool ReallyNeedsExt = false;
10693 if (N->getOpcode() != ISD::ANY_EXTEND) {
10694 // If all of the inputs are not already sign/zero extended, then
10695 // we'll still need to do that at the end.
10696 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10697 if (isa<ConstantSDNode>(Inputs[i]))
10701 Inputs[i].getOperand(0).getValueSizeInBits();
10702 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
10704 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
10705 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
10706 APInt::getHighBitsSet(OpBits,
10707 OpBits-PromBits))) ||
10708 (N->getOpcode() == ISD::SIGN_EXTEND &&
10709 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
10710 (OpBits-(PromBits-1)))) {
10711 ReallyNeedsExt = true;
10717 // Replace all inputs, either with the truncation operand, or a
10718 // truncation or extension to the final output type.
10719 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10720 // Constant inputs need to be replaced with the to-be-promoted nodes that
10721 // use them because they might have users outside of the cluster of
10723 if (isa<ConstantSDNode>(Inputs[i]))
10726 SDValue InSrc = Inputs[i].getOperand(0);
10727 if (Inputs[i].getValueType() == N->getValueType(0))
10728 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
10729 else if (N->getOpcode() == ISD::SIGN_EXTEND)
10730 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10731 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
10732 else if (N->getOpcode() == ISD::ZERO_EXTEND)
10733 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10734 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
10736 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10737 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
10740 std::list<HandleSDNode> PromOpHandles;
10741 for (auto &PromOp : PromOps)
10742 PromOpHandles.emplace_back(PromOp);
10744 // Replace all operations (these are all the same, but have a different
10745 // (promoted) return type). DAG.getNode will validate that the types of
10746 // a binary operator match, so go through the list in reverse so that
10747 // we've likely promoted both operands first.
10748 while (!PromOpHandles.empty()) {
10749 SDValue PromOp = PromOpHandles.back().getValue();
10750 PromOpHandles.pop_back();
10753 switch (PromOp.getOpcode()) {
10754 default: C = 0; break;
10755 case ISD::SELECT: C = 1; break;
10756 case ISD::SELECT_CC: C = 2; break;
10759 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10760 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
10761 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10762 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
10763 // The to-be-promoted operands of this node have not yet been
10764 // promoted (this should be rare because we're going through the
10765 // list backward, but if one of the operands has several users in
10766 // this cluster of to-be-promoted nodes, it is possible).
10767 PromOpHandles.emplace_front(PromOp);
10771 // For SELECT and SELECT_CC nodes, we do a similar check for any
10772 // to-be-promoted comparison inputs.
10773 if (PromOp.getOpcode() == ISD::SELECT ||
10774 PromOp.getOpcode() == ISD::SELECT_CC) {
10775 if ((SelectTruncOp[0].count(PromOp.getNode()) &&
10776 PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
10777 (SelectTruncOp[1].count(PromOp.getNode()) &&
10778 PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
10779 PromOpHandles.emplace_front(PromOp);
10784 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10785 PromOp.getNode()->op_end());
10787 // If this node has constant inputs, then they'll need to be promoted here.
10788 for (unsigned i = 0; i < 2; ++i) {
10789 if (!isa<ConstantSDNode>(Ops[C+i]))
10791 if (Ops[C+i].getValueType() == N->getValueType(0))
10794 if (N->getOpcode() == ISD::SIGN_EXTEND)
10795 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10796 else if (N->getOpcode() == ISD::ZERO_EXTEND)
10797 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10799 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10802 // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
10803 // truncate them again to the original value type.
10804 if (PromOp.getOpcode() == ISD::SELECT ||
10805 PromOp.getOpcode() == ISD::SELECT_CC) {
10806 auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
10807 if (SI0 != SelectTruncOp[0].end())
10808 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
10809 auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
10810 if (SI1 != SelectTruncOp[1].end())
10811 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
10814 DAG.ReplaceAllUsesOfValueWith(PromOp,
10815 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
10818 // Now we're left with the initial extension itself.
10819 if (!ReallyNeedsExt)
10820 return N->getOperand(0);
10822 // To zero extend, just mask off everything except for the first bit (in the
10824 if (N->getOpcode() == ISD::ZERO_EXTEND)
10825 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
10826 DAG.getConstant(APInt::getLowBitsSet(
10827 N->getValueSizeInBits(0), PromBits),
10828 dl, N->getValueType(0)));
10830 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
10831 "Invalid extension type");
10832 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
10834 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
10835 return DAG.getNode(
10836 ISD::SRA, dl, N->getValueType(0),
10837 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
10841 /// \brief Reduces the number of fp-to-int conversion when building a vector.
10843 /// If this vector is built out of floating to integer conversions,
10844 /// transform it to a vector built out of floating point values followed by a
10845 /// single floating to integer conversion of the vector.
10846 /// Namely (build_vector (fptosi $A), (fptosi $B), ...)
10847 /// becomes (fptosi (build_vector ($A, $B, ...)))
10848 SDValue PPCTargetLowering::
10849 combineElementTruncationToVectorTruncation(SDNode *N,
10850 DAGCombinerInfo &DCI) const {
10851 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
10852 "Should be called with a BUILD_VECTOR node");
10854 SelectionDAG &DAG = DCI.DAG;
10857 SDValue FirstInput = N->getOperand(0);
10858 assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
10859 "The input operand must be an fp-to-int conversion.");
10861 // This combine happens after legalization so the fp_to_[su]i nodes are
10862 // already converted to PPCSISD nodes.
10863 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
10864 if (FirstConversion == PPCISD::FCTIDZ ||
10865 FirstConversion == PPCISD::FCTIDUZ ||
10866 FirstConversion == PPCISD::FCTIWZ ||
10867 FirstConversion == PPCISD::FCTIWUZ) {
10868 bool IsSplat = true;
10869 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
10870 FirstConversion == PPCISD::FCTIWUZ;
10871 EVT SrcVT = FirstInput.getOperand(0).getValueType();
10872 SmallVector<SDValue, 4> Ops;
10873 EVT TargetVT = N->getValueType(0);
10874 for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
10875 if (N->getOperand(i).getOpcode() != PPCISD::MFVSR)
10877 unsigned NextConversion = N->getOperand(i).getOperand(0).getOpcode();
10878 if (NextConversion != FirstConversion)
10880 if (N->getOperand(i) != FirstInput)
10884 // If this is a splat, we leave it as-is since there will be only a single
10885 // fp-to-int conversion followed by a splat of the integer. This is better
10886 // for 32-bit and smaller ints and neutral for 64-bit ints.
10890 // Now that we know we have the right type of node, get its operands
10891 for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
10892 SDValue In = N->getOperand(i).getOperand(0);
10893 // For 32-bit values, we need to add an FP_ROUND node.
10896 Ops.push_back(DAG.getUNDEF(SrcVT));
10898 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
10899 MVT::f32, In.getOperand(0),
10900 DAG.getIntPtrConstant(1, dl));
10901 Ops.push_back(Trunc);
10904 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
10908 if (FirstConversion == PPCISD::FCTIDZ ||
10909 FirstConversion == PPCISD::FCTIWZ)
10910 Opcode = ISD::FP_TO_SINT;
10912 Opcode = ISD::FP_TO_UINT;
10914 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
10915 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
10916 return DAG.getNode(Opcode, dl, TargetVT, BV);
10921 /// \brief Reduce the number of loads when building a vector.
10923 /// Building a vector out of multiple loads can be converted to a load
10924 /// of the vector type if the loads are consecutive. If the loads are
10925 /// consecutive but in descending order, a shuffle is added at the end
10926 /// to reorder the vector.
10927 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
10928 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
10929 "Should be called with a BUILD_VECTOR node");
10932 bool InputsAreConsecutiveLoads = true;
10933 bool InputsAreReverseConsecutive = true;
10934 unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8;
10935 SDValue FirstInput = N->getOperand(0);
10936 bool IsRoundOfExtLoad = false;
10938 if (FirstInput.getOpcode() == ISD::FP_ROUND &&
10939 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
10940 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
10941 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
10943 // Not a build vector of (possibly fp_rounded) loads.
10944 if (!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD)
10947 for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
10948 // If any inputs are fp_round(extload), they all must be.
10949 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
10952 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
10954 if (NextInput.getOpcode() != ISD::LOAD)
10957 SDValue PreviousInput =
10958 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
10959 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
10960 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
10962 // If any inputs are fp_round(extload), they all must be.
10963 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
10966 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
10967 InputsAreConsecutiveLoads = false;
10968 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
10969 InputsAreReverseConsecutive = false;
10971 // Exit early if the loads are neither consecutive nor reverse consecutive.
10972 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
10976 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
10977 "The loads cannot be both consecutive and reverse consecutive.");
10979 SDValue FirstLoadOp =
10980 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
10981 SDValue LastLoadOp =
10982 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
10983 N->getOperand(N->getNumOperands()-1);
10985 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
10986 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
10987 if (InputsAreConsecutiveLoads) {
10988 assert(LD1 && "Input needs to be a LoadSDNode.");
10989 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
10990 LD1->getBasePtr(), LD1->getPointerInfo(),
10991 LD1->getAlignment());
10993 if (InputsAreReverseConsecutive) {
10994 assert(LDL && "Input needs to be a LoadSDNode.");
10995 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
10996 LDL->getBasePtr(), LDL->getPointerInfo(),
10997 LDL->getAlignment());
10998 SmallVector<int, 16> Ops;
10999 for (int i = N->getNumOperands() - 1; i >= 0; i--)
11002 return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
11003 DAG.getUNDEF(N->getValueType(0)), Ops);
11008 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
11009 DAGCombinerInfo &DCI) const {
11010 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11011 "Should be called with a BUILD_VECTOR node");
11013 SelectionDAG &DAG = DCI.DAG;
11016 if (!Subtarget.hasVSX())
11019 // The target independent DAG combiner will leave a build_vector of
11020 // float-to-int conversions intact. We can generate MUCH better code for
11021 // a float-to-int conversion of a vector of floats.
11022 SDValue FirstInput = N->getOperand(0);
11023 if (FirstInput.getOpcode() == PPCISD::MFVSR) {
11024 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
11029 // If we're building a vector out of consecutive loads, just load that
11031 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
11035 if (N->getValueType(0) != MVT::v2f64)
11039 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
11040 if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
11041 FirstInput.getOpcode() != ISD::UINT_TO_FP)
11043 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
11044 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
11046 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
11049 SDValue Ext1 = FirstInput.getOperand(0);
11050 SDValue Ext2 = N->getOperand(1).getOperand(0);
11051 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11052 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11055 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
11056 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
11057 if (!Ext1Op || !Ext2Op)
11059 if (Ext1.getValueType() != MVT::i32 ||
11060 Ext2.getValueType() != MVT::i32)
11061 if (Ext1.getOperand(0) != Ext2.getOperand(0))
11064 int FirstElem = Ext1Op->getZExtValue();
11065 int SecondElem = Ext2Op->getZExtValue();
11067 if (FirstElem == 0 && SecondElem == 1)
11068 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
11069 else if (FirstElem == 2 && SecondElem == 3)
11070 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
11074 SDValue SrcVec = Ext1.getOperand(0);
11075 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
11076 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
11077 return DAG.getNode(NodeType, dl, MVT::v2f64,
11078 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
11081 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
11082 DAGCombinerInfo &DCI) const {
11083 assert((N->getOpcode() == ISD::SINT_TO_FP ||
11084 N->getOpcode() == ISD::UINT_TO_FP) &&
11085 "Need an int -> FP conversion node here");
11087 if (useSoftFloat() || !Subtarget.has64BitSupport())
11090 SelectionDAG &DAG = DCI.DAG;
11094 SDValue FirstOperand(Op.getOperand(0));
11095 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
11096 (FirstOperand.getValueType() == MVT::i8 ||
11097 FirstOperand.getValueType() == MVT::i16);
11098 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
11099 bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
11100 bool DstDouble = Op.getValueType() == MVT::f64;
11101 unsigned ConvOp = Signed ?
11102 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) :
11103 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
11104 SDValue WidthConst =
11105 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
11107 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
11108 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
11109 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
11110 DAG.getVTList(MVT::f64, MVT::Other),
11111 Ops, MVT::i8, LDN->getMemOperand());
11113 // For signed conversion, we need to sign-extend the value in the VSR
11115 SDValue ExtOps[] = { Ld, WidthConst };
11116 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
11117 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
11119 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
11122 // Don't handle ppc_fp128 here or i1 conversions.
11123 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
11125 if (Op.getOperand(0).getValueType() == MVT::i1)
11128 // For i32 intermediate values, unfortunately, the conversion functions
11129 // leave the upper 32 bits of the value are undefined. Within the set of
11130 // scalar instructions, we have no method for zero- or sign-extending the
11131 // value. Thus, we cannot handle i32 intermediate values here.
11132 if (Op.getOperand(0).getValueType() == MVT::i32)
11135 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
11136 "UINT_TO_FP is supported only with FPCVT");
11138 // If we have FCFIDS, then use it when converting to single-precision.
11139 // Otherwise, convert to double-precision and then round.
11140 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11141 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
11143 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
11145 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11149 // If we're converting from a float, to an int, and back to a float again,
11150 // then we don't need the store/load pair at all.
11151 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
11152 Subtarget.hasFPCVT()) ||
11153 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
11154 SDValue Src = Op.getOperand(0).getOperand(0);
11155 if (Src.getValueType() == MVT::f32) {
11156 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
11157 DCI.AddToWorklist(Src.getNode());
11158 } else if (Src.getValueType() != MVT::f64) {
11159 // Make sure that we don't pick up a ppc_fp128 source value.
11164 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
11167 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
11168 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
11170 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
11171 FP = DAG.getNode(ISD::FP_ROUND, dl,
11172 MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
11173 DCI.AddToWorklist(FP.getNode());
11182 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
11183 // builtins) into loads with swaps.
11184 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
11185 DAGCombinerInfo &DCI) const {
11186 SelectionDAG &DAG = DCI.DAG;
11190 MachineMemOperand *MMO;
11192 switch (N->getOpcode()) {
11194 llvm_unreachable("Unexpected opcode for little endian VSX load");
11196 LoadSDNode *LD = cast<LoadSDNode>(N);
11197 Chain = LD->getChain();
11198 Base = LD->getBasePtr();
11199 MMO = LD->getMemOperand();
11200 // If the MMO suggests this isn't a load of a full vector, leave
11201 // things alone. For a built-in, we have to make the change for
11202 // correctness, so if there is a size problem that will be a bug.
11203 if (MMO->getSize() < 16)
11207 case ISD::INTRINSIC_W_CHAIN: {
11208 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
11209 Chain = Intrin->getChain();
11210 // Similarly to the store case below, Intrin->getBasePtr() doesn't get
11211 // us what we want. Get operand 2 instead.
11212 Base = Intrin->getOperand(2);
11213 MMO = Intrin->getMemOperand();
11218 MVT VecTy = N->getValueType(0).getSimpleVT();
11219 SDValue LoadOps[] = { Chain, Base };
11220 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
11221 DAG.getVTList(MVT::v2f64, MVT::Other),
11222 LoadOps, MVT::v2f64, MMO);
11224 DCI.AddToWorklist(Load.getNode());
11225 Chain = Load.getValue(1);
11226 SDValue Swap = DAG.getNode(
11227 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
11228 DCI.AddToWorklist(Swap.getNode());
11230 // Add a bitcast if the resulting load type doesn't match v2f64.
11231 if (VecTy != MVT::v2f64) {
11232 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
11233 DCI.AddToWorklist(N.getNode());
11234 // Package {bitcast value, swap's chain} to match Load's shape.
11235 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
11236 N, Swap.getValue(1));
11242 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
11243 // builtins) into stores with swaps.
11244 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
11245 DAGCombinerInfo &DCI) const {
11246 SelectionDAG &DAG = DCI.DAG;
11251 MachineMemOperand *MMO;
11253 switch (N->getOpcode()) {
11255 llvm_unreachable("Unexpected opcode for little endian VSX store");
11257 StoreSDNode *ST = cast<StoreSDNode>(N);
11258 Chain = ST->getChain();
11259 Base = ST->getBasePtr();
11260 MMO = ST->getMemOperand();
11262 // If the MMO suggests this isn't a store of a full vector, leave
11263 // things alone. For a built-in, we have to make the change for
11264 // correctness, so if there is a size problem that will be a bug.
11265 if (MMO->getSize() < 16)
11269 case ISD::INTRINSIC_VOID: {
11270 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
11271 Chain = Intrin->getChain();
11272 // Intrin->getBasePtr() oddly does not get what we want.
11273 Base = Intrin->getOperand(3);
11274 MMO = Intrin->getMemOperand();
11280 SDValue Src = N->getOperand(SrcOpnd);
11281 MVT VecTy = Src.getValueType().getSimpleVT();
11283 // All stores are done as v2f64 and possible bit cast.
11284 if (VecTy != MVT::v2f64) {
11285 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
11286 DCI.AddToWorklist(Src.getNode());
11289 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
11290 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
11291 DCI.AddToWorklist(Swap.getNode());
11292 Chain = Swap.getValue(1);
11293 SDValue StoreOps[] = { Chain, Swap, Base };
11294 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
11295 DAG.getVTList(MVT::Other),
11296 StoreOps, VecTy, MMO);
11297 DCI.AddToWorklist(Store.getNode());
11301 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
11302 DAGCombinerInfo &DCI) const {
11303 SelectionDAG &DAG = DCI.DAG;
11305 switch (N->getOpcode()) {
11308 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
11309 return N->getOperand(0);
11312 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
11313 return N->getOperand(0);
11316 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11317 if (C->isNullValue() || // 0 >>s V -> 0.
11318 C->isAllOnesValue()) // -1 >>s V -> -1.
11319 return N->getOperand(0);
11322 case ISD::SIGN_EXTEND:
11323 case ISD::ZERO_EXTEND:
11324 case ISD::ANY_EXTEND:
11325 return DAGCombineExtBoolTrunc(N, DCI);
11326 case ISD::TRUNCATE:
11328 case ISD::SELECT_CC:
11329 return DAGCombineTruncBoolExt(N, DCI);
11330 case ISD::SINT_TO_FP:
11331 case ISD::UINT_TO_FP:
11332 return combineFPToIntToFP(N, DCI);
11334 EVT Op1VT = N->getOperand(1).getValueType();
11335 bool ValidTypeForStoreFltAsInt = (Op1VT == MVT::i32) ||
11336 (Subtarget.hasP9Vector() && (Op1VT == MVT::i8 || Op1VT == MVT::i16));
11338 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
11339 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
11340 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
11341 ValidTypeForStoreFltAsInt &&
11342 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
11343 SDValue Val = N->getOperand(1).getOperand(0);
11344 if (Val.getValueType() == MVT::f32) {
11345 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
11346 DCI.AddToWorklist(Val.getNode());
11348 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
11349 DCI.AddToWorklist(Val.getNode());
11351 if (Op1VT == MVT::i32) {
11353 N->getOperand(0), Val, N->getOperand(2),
11354 DAG.getValueType(N->getOperand(1).getValueType())
11357 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
11358 DAG.getVTList(MVT::Other), Ops,
11359 cast<StoreSDNode>(N)->getMemoryVT(),
11360 cast<StoreSDNode>(N)->getMemOperand());
11362 unsigned WidthInBytes =
11363 N->getOperand(1).getValueType() == MVT::i8 ? 1 : 2;
11364 SDValue WidthConst = DAG.getIntPtrConstant(WidthInBytes, dl, false);
11367 N->getOperand(0), Val, N->getOperand(2), WidthConst,
11368 DAG.getValueType(N->getOperand(1).getValueType())
11370 Val = DAG.getMemIntrinsicNode(PPCISD::STXSIX, dl,
11371 DAG.getVTList(MVT::Other), Ops,
11372 cast<StoreSDNode>(N)->getMemoryVT(),
11373 cast<StoreSDNode>(N)->getMemOperand());
11376 DCI.AddToWorklist(Val.getNode());
11380 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
11381 if (cast<StoreSDNode>(N)->isUnindexed() &&
11382 N->getOperand(1).getOpcode() == ISD::BSWAP &&
11383 N->getOperand(1).getNode()->hasOneUse() &&
11384 (N->getOperand(1).getValueType() == MVT::i32 ||
11385 N->getOperand(1).getValueType() == MVT::i16 ||
11386 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
11387 N->getOperand(1).getValueType() == MVT::i64))) {
11388 SDValue BSwapOp = N->getOperand(1).getOperand(0);
11389 // Do an any-extend to 32-bits if this is a half-word input.
11390 if (BSwapOp.getValueType() == MVT::i16)
11391 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
11393 // If the type of BSWAP operand is wider than stored memory width
11394 // it need to be shifted to the right side before STBRX.
11395 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
11396 if (Op1VT.bitsGT(mVT)) {
11397 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
11398 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
11399 DAG.getConstant(Shift, dl, MVT::i32));
11400 // Need to truncate if this is a bswap of i64 stored as i32/i16.
11401 if (Op1VT == MVT::i64)
11402 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
11406 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
11409 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
11410 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
11411 cast<StoreSDNode>(N)->getMemOperand());
11414 // For little endian, VSX stores require generating xxswapd/lxvd2x.
11415 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
11416 EVT VT = N->getOperand(1).getValueType();
11417 if (VT.isSimple()) {
11418 MVT StoreVT = VT.getSimpleVT();
11419 if (Subtarget.needsSwapsForVSXMemOps() &&
11420 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
11421 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
11422 return expandVSXStoreForLE(N, DCI);
11427 LoadSDNode *LD = cast<LoadSDNode>(N);
11428 EVT VT = LD->getValueType(0);
11430 // For little endian, VSX loads require generating lxvd2x/xxswapd.
11431 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
11432 if (VT.isSimple()) {
11433 MVT LoadVT = VT.getSimpleVT();
11434 if (Subtarget.needsSwapsForVSXMemOps() &&
11435 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
11436 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
11437 return expandVSXLoadForLE(N, DCI);
11440 // We sometimes end up with a 64-bit integer load, from which we extract
11441 // two single-precision floating-point numbers. This happens with
11442 // std::complex<float>, and other similar structures, because of the way we
11443 // canonicalize structure copies. However, if we lack direct moves,
11444 // then the final bitcasts from the extracted integer values to the
11445 // floating-point numbers turn into store/load pairs. Even with direct moves,
11446 // just loading the two floating-point numbers is likely better.
11447 auto ReplaceTwoFloatLoad = [&]() {
11448 if (VT != MVT::i64)
11451 if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
11455 // We're looking for a sequence like this:
11456 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
11457 // t16: i64 = srl t13, Constant:i32<32>
11458 // t17: i32 = truncate t16
11459 // t18: f32 = bitcast t17
11460 // t19: i32 = truncate t13
11461 // t20: f32 = bitcast t19
11463 if (!LD->hasNUsesOfValue(2, 0))
11466 auto UI = LD->use_begin();
11467 while (UI.getUse().getResNo() != 0) ++UI;
11468 SDNode *Trunc = *UI++;
11469 while (UI.getUse().getResNo() != 0) ++UI;
11470 SDNode *RightShift = *UI;
11471 if (Trunc->getOpcode() != ISD::TRUNCATE)
11472 std::swap(Trunc, RightShift);
11474 if (Trunc->getOpcode() != ISD::TRUNCATE ||
11475 Trunc->getValueType(0) != MVT::i32 ||
11476 !Trunc->hasOneUse())
11478 if (RightShift->getOpcode() != ISD::SRL ||
11479 !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
11480 RightShift->getConstantOperandVal(1) != 32 ||
11481 !RightShift->hasOneUse())
11484 SDNode *Trunc2 = *RightShift->use_begin();
11485 if (Trunc2->getOpcode() != ISD::TRUNCATE ||
11486 Trunc2->getValueType(0) != MVT::i32 ||
11487 !Trunc2->hasOneUse())
11490 SDNode *Bitcast = *Trunc->use_begin();
11491 SDNode *Bitcast2 = *Trunc2->use_begin();
11493 if (Bitcast->getOpcode() != ISD::BITCAST ||
11494 Bitcast->getValueType(0) != MVT::f32)
11496 if (Bitcast2->getOpcode() != ISD::BITCAST ||
11497 Bitcast2->getValueType(0) != MVT::f32)
11500 if (Subtarget.isLittleEndian())
11501 std::swap(Bitcast, Bitcast2);
11503 // Bitcast has the second float (in memory-layout order) and Bitcast2
11504 // has the first one.
11506 SDValue BasePtr = LD->getBasePtr();
11507 if (LD->isIndexed()) {
11508 assert(LD->getAddressingMode() == ISD::PRE_INC &&
11509 "Non-pre-inc AM on PPC?");
11511 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
11516 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
11517 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
11518 LD->getPointerInfo(), LD->getAlignment(),
11519 MMOFlags, LD->getAAInfo());
11521 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
11522 BasePtr, DAG.getIntPtrConstant(4, dl));
11523 SDValue FloatLoad2 = DAG.getLoad(
11524 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
11525 LD->getPointerInfo().getWithOffset(4),
11526 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
11528 if (LD->isIndexed()) {
11529 // Note that DAGCombine should re-form any pre-increment load(s) from
11530 // what is produced here if that makes sense.
11531 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
11534 DCI.CombineTo(Bitcast2, FloatLoad);
11535 DCI.CombineTo(Bitcast, FloatLoad2);
11537 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
11538 SDValue(FloatLoad2.getNode(), 1));
11542 if (ReplaceTwoFloatLoad())
11543 return SDValue(N, 0);
11545 EVT MemVT = LD->getMemoryVT();
11546 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
11547 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
11548 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
11549 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
11550 if (LD->isUnindexed() && VT.isVector() &&
11551 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
11552 // P8 and later hardware should just use LOAD.
11553 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
11554 VT == MVT::v4i32 || VT == MVT::v4f32)) ||
11555 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
11556 LD->getAlignment() >= ScalarABIAlignment)) &&
11557 LD->getAlignment() < ABIAlignment) {
11558 // This is a type-legal unaligned Altivec or QPX load.
11559 SDValue Chain = LD->getChain();
11560 SDValue Ptr = LD->getBasePtr();
11561 bool isLittleEndian = Subtarget.isLittleEndian();
11563 // This implements the loading of unaligned vectors as described in
11564 // the venerable Apple Velocity Engine overview. Specifically:
11565 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
11566 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
11568 // The general idea is to expand a sequence of one or more unaligned
11569 // loads into an alignment-based permutation-control instruction (lvsl
11570 // or lvsr), a series of regular vector loads (which always truncate
11571 // their input address to an aligned address), and a series of
11572 // permutations. The results of these permutations are the requested
11573 // loaded values. The trick is that the last "extra" load is not taken
11574 // from the address you might suspect (sizeof(vector) bytes after the
11575 // last requested load), but rather sizeof(vector) - 1 bytes after the
11576 // last requested vector. The point of this is to avoid a page fault if
11577 // the base address happened to be aligned. This works because if the
11578 // base address is aligned, then adding less than a full vector length
11579 // will cause the last vector in the sequence to be (re)loaded.
11580 // Otherwise, the next vector will be fetched as you might suspect was
11583 // We might be able to reuse the permutation generation from
11584 // a different base address offset from this one by an aligned amount.
11585 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
11586 // optimization later.
11587 Intrinsic::ID Intr, IntrLD, IntrPerm;
11588 MVT PermCntlTy, PermTy, LDTy;
11589 if (Subtarget.hasAltivec()) {
11590 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr :
11591 Intrinsic::ppc_altivec_lvsl;
11592 IntrLD = Intrinsic::ppc_altivec_lvx;
11593 IntrPerm = Intrinsic::ppc_altivec_vperm;
11594 PermCntlTy = MVT::v16i8;
11595 PermTy = MVT::v4i32;
11598 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
11599 Intrinsic::ppc_qpx_qvlpcls;
11600 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
11601 Intrinsic::ppc_qpx_qvlfs;
11602 IntrPerm = Intrinsic::ppc_qpx_qvfperm;
11603 PermCntlTy = MVT::v4f64;
11604 PermTy = MVT::v4f64;
11605 LDTy = MemVT.getSimpleVT();
11608 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
11610 // Create the new MMO for the new base load. It is like the original MMO,
11611 // but represents an area in memory almost twice the vector size centered
11612 // on the original address. If the address is unaligned, we might start
11613 // reading up to (sizeof(vector)-1) bytes below the address of the
11614 // original unaligned load.
11615 MachineFunction &MF = DAG.getMachineFunction();
11616 MachineMemOperand *BaseMMO =
11617 MF.getMachineMemOperand(LD->getMemOperand(),
11618 -(long)MemVT.getStoreSize()+1,
11619 2*MemVT.getStoreSize()-1);
11621 // Create the new base load.
11623 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
11624 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
11626 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
11627 DAG.getVTList(PermTy, MVT::Other),
11628 BaseLoadOps, LDTy, BaseMMO);
11630 // Note that the value of IncOffset (which is provided to the next
11631 // load's pointer info offset value, and thus used to calculate the
11632 // alignment), and the value of IncValue (which is actually used to
11633 // increment the pointer value) are different! This is because we
11634 // require the next load to appear to be aligned, even though it
11635 // is actually offset from the base pointer by a lesser amount.
11636 int IncOffset = VT.getSizeInBits() / 8;
11637 int IncValue = IncOffset;
11639 // Walk (both up and down) the chain looking for another load at the real
11640 // (aligned) offset (the alignment of the other load does not matter in
11641 // this case). If found, then do not use the offset reduction trick, as
11642 // that will prevent the loads from being later combined (as they would
11643 // otherwise be duplicates).
11644 if (!findConsecutiveLoad(LD, DAG))
11647 SDValue Increment =
11648 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
11649 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
11651 MachineMemOperand *ExtraMMO =
11652 MF.getMachineMemOperand(LD->getMemOperand(),
11653 1, 2*MemVT.getStoreSize()-1);
11654 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
11655 SDValue ExtraLoad =
11656 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
11657 DAG.getVTList(PermTy, MVT::Other),
11658 ExtraLoadOps, LDTy, ExtraMMO);
11660 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
11661 BaseLoad.getValue(1), ExtraLoad.getValue(1));
11663 // Because vperm has a big-endian bias, we must reverse the order
11664 // of the input vectors and complement the permute control vector
11665 // when generating little endian code. We have already handled the
11666 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
11667 // and ExtraLoad here.
11669 if (isLittleEndian)
11670 Perm = BuildIntrinsicOp(IntrPerm,
11671 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
11673 Perm = BuildIntrinsicOp(IntrPerm,
11674 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
11677 Perm = Subtarget.hasAltivec() ?
11678 DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
11679 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
11680 DAG.getTargetConstant(1, dl, MVT::i64));
11681 // second argument is 1 because this rounding
11682 // is always exact.
11684 // The output of the permutation is our loaded result, the TokenFactor is
11686 DCI.CombineTo(N, Perm, TF);
11687 return SDValue(N, 0);
11691 case ISD::INTRINSIC_WO_CHAIN: {
11692 bool isLittleEndian = Subtarget.isLittleEndian();
11693 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11694 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
11695 : Intrinsic::ppc_altivec_lvsl);
11696 if ((IID == Intr ||
11697 IID == Intrinsic::ppc_qpx_qvlpcld ||
11698 IID == Intrinsic::ppc_qpx_qvlpcls) &&
11699 N->getOperand(1)->getOpcode() == ISD::ADD) {
11700 SDValue Add = N->getOperand(1);
11702 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
11703 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
11705 if (DAG.MaskedValueIsZero(Add->getOperand(1),
11706 APInt::getAllOnesValue(Bits /* alignment */)
11707 .zext(Add.getScalarValueSizeInBits()))) {
11708 SDNode *BasePtr = Add->getOperand(0).getNode();
11709 for (SDNode::use_iterator UI = BasePtr->use_begin(),
11710 UE = BasePtr->use_end();
11712 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11713 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
11714 // We've found another LVSL/LVSR, and this address is an aligned
11715 // multiple of that one. The results will be the same, so use the
11716 // one we've just found instead.
11718 return SDValue(*UI, 0);
11723 if (isa<ConstantSDNode>(Add->getOperand(1))) {
11724 SDNode *BasePtr = Add->getOperand(0).getNode();
11725 for (SDNode::use_iterator UI = BasePtr->use_begin(),
11726 UE = BasePtr->use_end(); UI != UE; ++UI) {
11727 if (UI->getOpcode() == ISD::ADD &&
11728 isa<ConstantSDNode>(UI->getOperand(1)) &&
11729 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
11730 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
11731 (1ULL << Bits) == 0) {
11732 SDNode *OtherAdd = *UI;
11733 for (SDNode::use_iterator VI = OtherAdd->use_begin(),
11734 VE = OtherAdd->use_end(); VI != VE; ++VI) {
11735 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11736 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
11737 return SDValue(*VI, 0);
11747 case ISD::INTRINSIC_W_CHAIN:
11748 // For little endian, VSX loads require generating lxvd2x/xxswapd.
11749 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
11750 if (Subtarget.needsSwapsForVSXMemOps()) {
11751 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11754 case Intrinsic::ppc_vsx_lxvw4x:
11755 case Intrinsic::ppc_vsx_lxvd2x:
11756 return expandVSXLoadForLE(N, DCI);
11760 case ISD::INTRINSIC_VOID:
11761 // For little endian, VSX stores require generating xxswapd/stxvd2x.
11762 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
11763 if (Subtarget.needsSwapsForVSXMemOps()) {
11764 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11767 case Intrinsic::ppc_vsx_stxvw4x:
11768 case Intrinsic::ppc_vsx_stxvd2x:
11769 return expandVSXStoreForLE(N, DCI);
11774 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
11775 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
11776 N->getOperand(0).hasOneUse() &&
11777 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
11778 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
11779 N->getValueType(0) == MVT::i64))) {
11780 SDValue Load = N->getOperand(0);
11781 LoadSDNode *LD = cast<LoadSDNode>(Load);
11782 // Create the byte-swapping load.
11784 LD->getChain(), // Chain
11785 LD->getBasePtr(), // Ptr
11786 DAG.getValueType(N->getValueType(0)) // VT
11789 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
11790 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
11791 MVT::i64 : MVT::i32, MVT::Other),
11792 Ops, LD->getMemoryVT(), LD->getMemOperand());
11794 // If this is an i16 load, insert the truncate.
11795 SDValue ResVal = BSLoad;
11796 if (N->getValueType(0) == MVT::i16)
11797 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
11799 // First, combine the bswap away. This makes the value produced by the
11801 DCI.CombineTo(N, ResVal);
11803 // Next, combine the load away, we give it a bogus result value but a real
11804 // chain result. The result value is dead because the bswap is dead.
11805 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
11807 // Return N so it doesn't get rechecked!
11808 return SDValue(N, 0);
11812 // If a VCMPo node already exists with exactly the same operands as this
11813 // node, use its result instead of this node (VCMPo computes both a CR6 and
11814 // a normal output).
11816 if (!N->getOperand(0).hasOneUse() &&
11817 !N->getOperand(1).hasOneUse() &&
11818 !N->getOperand(2).hasOneUse()) {
11820 // Scan all of the users of the LHS, looking for VCMPo's that match.
11821 SDNode *VCMPoNode = nullptr;
11823 SDNode *LHSN = N->getOperand(0).getNode();
11824 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
11826 if (UI->getOpcode() == PPCISD::VCMPo &&
11827 UI->getOperand(1) == N->getOperand(1) &&
11828 UI->getOperand(2) == N->getOperand(2) &&
11829 UI->getOperand(0) == N->getOperand(0)) {
11834 // If there is no VCMPo node, or if the flag value has a single use, don't
11836 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
11839 // Look at the (necessarily single) use of the flag value. If it has a
11840 // chain, this transformation is more complex. Note that multiple things
11841 // could use the value result, which we should ignore.
11842 SDNode *FlagUser = nullptr;
11843 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
11844 FlagUser == nullptr; ++UI) {
11845 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
11846 SDNode *User = *UI;
11847 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
11848 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
11855 // If the user is a MFOCRF instruction, we know this is safe.
11856 // Otherwise we give up for right now.
11857 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
11858 return SDValue(VCMPoNode, 0);
11861 case ISD::BRCOND: {
11862 SDValue Cond = N->getOperand(1);
11863 SDValue Target = N->getOperand(2);
11865 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11866 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
11867 Intrinsic::ppc_is_decremented_ctr_nonzero) {
11869 // We now need to make the intrinsic dead (it cannot be instruction
11871 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
11872 assert(Cond.getNode()->hasOneUse() &&
11873 "Counter decrement has more than one use");
11875 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
11876 N->getOperand(0), Target);
11881 // If this is a branch on an altivec predicate comparison, lower this so
11882 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
11883 // lowering is done pre-legalize, because the legalizer lowers the predicate
11884 // compare down to code that is difficult to reassemble.
11885 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
11886 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
11888 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
11889 // value. If so, pass-through the AND to get to the intrinsic.
11890 if (LHS.getOpcode() == ISD::AND &&
11891 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11892 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
11893 Intrinsic::ppc_is_decremented_ctr_nonzero &&
11894 isa<ConstantSDNode>(LHS.getOperand(1)) &&
11895 !isNullConstant(LHS.getOperand(1)))
11896 LHS = LHS.getOperand(0);
11898 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11899 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
11900 Intrinsic::ppc_is_decremented_ctr_nonzero &&
11901 isa<ConstantSDNode>(RHS)) {
11902 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11903 "Counter decrement comparison is not EQ or NE");
11905 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11906 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
11907 (CC == ISD::SETNE && !Val);
11909 // We now need to make the intrinsic dead (it cannot be instruction
11911 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
11912 assert(LHS.getNode()->hasOneUse() &&
11913 "Counter decrement has more than one use");
11915 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
11916 N->getOperand(0), N->getOperand(4));
11922 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11923 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
11924 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
11925 assert(isDot && "Can't compare against a vector result!");
11927 // If this is a comparison against something other than 0/1, then we know
11928 // that the condition is never/always true.
11929 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11930 if (Val != 0 && Val != 1) {
11931 if (CC == ISD::SETEQ) // Cond never true, remove branch.
11932 return N->getOperand(0);
11933 // Always !=, turn it into an unconditional branch.
11934 return DAG.getNode(ISD::BR, dl, MVT::Other,
11935 N->getOperand(0), N->getOperand(4));
11938 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
11940 // Create the PPCISD altivec 'dot' comparison node.
11942 LHS.getOperand(2), // LHS of compare
11943 LHS.getOperand(3), // RHS of compare
11944 DAG.getConstant(CompareOpc, dl, MVT::i32)
11946 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
11947 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
11949 // Unpack the result based on how the target uses it.
11950 PPC::Predicate CompOpc;
11951 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
11952 default: // Can't happen, don't crash on invalid number though.
11953 case 0: // Branch on the value of the EQ bit of CR6.
11954 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
11956 case 1: // Branch on the inverted value of the EQ bit of CR6.
11957 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
11959 case 2: // Branch on the value of the LT bit of CR6.
11960 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
11962 case 3: // Branch on the inverted value of the LT bit of CR6.
11963 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
11967 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
11968 DAG.getConstant(CompOpc, dl, MVT::i32),
11969 DAG.getRegister(PPC::CR6, MVT::i32),
11970 N->getOperand(4), CompNode.getValue(1));
11974 case ISD::BUILD_VECTOR:
11975 return DAGCombineBuildVector(N, DCI);
11982 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11984 std::vector<SDNode *> *Created) const {
11985 // fold (sdiv X, pow2)
11986 EVT VT = N->getValueType(0);
11987 if (VT == MVT::i64 && !Subtarget.isPPC64())
11989 if ((VT != MVT::i32 && VT != MVT::i64) ||
11990 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
11994 SDValue N0 = N->getOperand(0);
11996 bool IsNegPow2 = (-Divisor).isPowerOf2();
11997 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
11998 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
12000 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
12002 Created->push_back(Op.getNode());
12005 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
12007 Created->push_back(Op.getNode());
12013 //===----------------------------------------------------------------------===//
12014 // Inline Assembly Support
12015 //===----------------------------------------------------------------------===//
12017 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12020 const APInt &DemandedElts,
12021 const SelectionDAG &DAG,
12022 unsigned Depth) const {
12023 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
12024 switch (Op.getOpcode()) {
12026 case PPCISD::LBRX: {
12027 // lhbrx is known to have the top bits cleared out.
12028 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
12029 KnownZero = 0xFFFF0000;
12032 case ISD::INTRINSIC_WO_CHAIN: {
12033 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
12035 case Intrinsic::ppc_altivec_vcmpbfp_p:
12036 case Intrinsic::ppc_altivec_vcmpeqfp_p:
12037 case Intrinsic::ppc_altivec_vcmpequb_p:
12038 case Intrinsic::ppc_altivec_vcmpequh_p:
12039 case Intrinsic::ppc_altivec_vcmpequw_p:
12040 case Intrinsic::ppc_altivec_vcmpequd_p:
12041 case Intrinsic::ppc_altivec_vcmpgefp_p:
12042 case Intrinsic::ppc_altivec_vcmpgtfp_p:
12043 case Intrinsic::ppc_altivec_vcmpgtsb_p:
12044 case Intrinsic::ppc_altivec_vcmpgtsh_p:
12045 case Intrinsic::ppc_altivec_vcmpgtsw_p:
12046 case Intrinsic::ppc_altivec_vcmpgtsd_p:
12047 case Intrinsic::ppc_altivec_vcmpgtub_p:
12048 case Intrinsic::ppc_altivec_vcmpgtuh_p:
12049 case Intrinsic::ppc_altivec_vcmpgtuw_p:
12050 case Intrinsic::ppc_altivec_vcmpgtud_p:
12051 KnownZero = ~1U; // All bits but the low one are known to be zero.
12058 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12059 switch (Subtarget.getDarwinDirective()) {
12062 case PPC::DIR_PWR4:
12063 case PPC::DIR_PWR5:
12064 case PPC::DIR_PWR5X:
12065 case PPC::DIR_PWR6:
12066 case PPC::DIR_PWR6X:
12067 case PPC::DIR_PWR7:
12068 case PPC::DIR_PWR8:
12069 case PPC::DIR_PWR9: {
12073 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
12075 // For small loops (between 5 and 8 instructions), align to a 32-byte
12076 // boundary so that the entire loop fits in one instruction-cache line.
12077 uint64_t LoopSize = 0;
12078 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
12079 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
12080 LoopSize += TII->getInstSizeInBytes(*J);
12085 if (LoopSize > 16 && LoopSize <= 32)
12092 return TargetLowering::getPrefLoopAlignment(ML);
12095 /// getConstraintType - Given a constraint, return the type of
12096 /// constraint it is for this target.
12097 PPCTargetLowering::ConstraintType
12098 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
12099 if (Constraint.size() == 1) {
12100 switch (Constraint[0]) {
12108 return C_RegisterClass;
12110 // FIXME: While Z does indicate a memory constraint, it specifically
12111 // indicates an r+r address (used in conjunction with the 'y' modifier
12112 // in the replacement string). Currently, we're forcing the base
12113 // register to be r0 in the asm printer (which is interpreted as zero)
12114 // and forming the complete address in the second register. This is
12118 } else if (Constraint == "wc") { // individual CR bits.
12119 return C_RegisterClass;
12120 } else if (Constraint == "wa" || Constraint == "wd" ||
12121 Constraint == "wf" || Constraint == "ws") {
12122 return C_RegisterClass; // VSX registers.
12124 return TargetLowering::getConstraintType(Constraint);
12127 /// Examine constraint type and operand type and determine a weight value.
12128 /// This object must already have been set up with the operand type
12129 /// and the current alternative constraint selected.
12130 TargetLowering::ConstraintWeight
12131 PPCTargetLowering::getSingleConstraintMatchWeight(
12132 AsmOperandInfo &info, const char *constraint) const {
12133 ConstraintWeight weight = CW_Invalid;
12134 Value *CallOperandVal = info.CallOperandVal;
12135 // If we don't have a value, we can't do a match,
12136 // but allow it at the lowest weight.
12137 if (!CallOperandVal)
12139 Type *type = CallOperandVal->getType();
12141 // Look at the constraint type.
12142 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
12143 return CW_Register; // an individual CR bit.
12144 else if ((StringRef(constraint) == "wa" ||
12145 StringRef(constraint) == "wd" ||
12146 StringRef(constraint) == "wf") &&
12147 type->isVectorTy())
12148 return CW_Register;
12149 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
12150 return CW_Register;
12152 switch (*constraint) {
12154 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12157 if (type->isIntegerTy())
12158 weight = CW_Register;
12161 if (type->isFloatTy())
12162 weight = CW_Register;
12165 if (type->isDoubleTy())
12166 weight = CW_Register;
12169 if (type->isVectorTy())
12170 weight = CW_Register;
12173 weight = CW_Register;
12176 weight = CW_Memory;
12182 std::pair<unsigned, const TargetRegisterClass *>
12183 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
12184 StringRef Constraint,
12186 if (Constraint.size() == 1) {
12187 // GCC RS6000 Constraint Letters
12188 switch (Constraint[0]) {
12189 case 'b': // R1-R31
12190 if (VT == MVT::i64 && Subtarget.isPPC64())
12191 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
12192 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
12193 case 'r': // R0-R31
12194 if (VT == MVT::i64 && Subtarget.isPPC64())
12195 return std::make_pair(0U, &PPC::G8RCRegClass);
12196 return std::make_pair(0U, &PPC::GPRCRegClass);
12197 // 'd' and 'f' constraints are both defined to be "the floating point
12198 // registers", where one is for 32-bit and the other for 64-bit. We don't
12199 // really care overly much here so just give them all the same reg classes.
12202 if (VT == MVT::f32 || VT == MVT::i32)
12203 return std::make_pair(0U, &PPC::F4RCRegClass);
12204 if (VT == MVT::f64 || VT == MVT::i64)
12205 return std::make_pair(0U, &PPC::F8RCRegClass);
12206 if (VT == MVT::v4f64 && Subtarget.hasQPX())
12207 return std::make_pair(0U, &PPC::QFRCRegClass);
12208 if (VT == MVT::v4f32 && Subtarget.hasQPX())
12209 return std::make_pair(0U, &PPC::QSRCRegClass);
12212 if (VT == MVT::v4f64 && Subtarget.hasQPX())
12213 return std::make_pair(0U, &PPC::QFRCRegClass);
12214 if (VT == MVT::v4f32 && Subtarget.hasQPX())
12215 return std::make_pair(0U, &PPC::QSRCRegClass);
12216 if (Subtarget.hasAltivec())
12217 return std::make_pair(0U, &PPC::VRRCRegClass);
12219 return std::make_pair(0U, &PPC::CRRCRegClass);
12221 } else if (Constraint == "wc" && Subtarget.useCRBits()) {
12222 // An individual CR bit.
12223 return std::make_pair(0U, &PPC::CRBITRCRegClass);
12224 } else if ((Constraint == "wa" || Constraint == "wd" ||
12225 Constraint == "wf") && Subtarget.hasVSX()) {
12226 return std::make_pair(0U, &PPC::VSRCRegClass);
12227 } else if (Constraint == "ws" && Subtarget.hasVSX()) {
12228 if (VT == MVT::f32 && Subtarget.hasP8Vector())
12229 return std::make_pair(0U, &PPC::VSSRCRegClass);
12231 return std::make_pair(0U, &PPC::VSFRCRegClass);
12234 std::pair<unsigned, const TargetRegisterClass *> R =
12235 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12237 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
12238 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
12239 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
12241 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
12242 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
12243 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
12244 PPC::GPRCRegClass.contains(R.first))
12245 return std::make_pair(TRI->getMatchingSuperReg(R.first,
12246 PPC::sub_32, &PPC::G8RCRegClass),
12247 &PPC::G8RCRegClass);
12249 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
12250 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
12251 R.first = PPC::CR0;
12252 R.second = &PPC::CRRCRegClass;
12258 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12259 /// vector. If it is invalid, don't add anything to Ops.
12260 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12261 std::string &Constraint,
12262 std::vector<SDValue>&Ops,
12263 SelectionDAG &DAG) const {
12266 // Only support length 1 constraints.
12267 if (Constraint.length() > 1) return;
12269 char Letter = Constraint[0];
12280 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
12281 if (!CST) return; // Must be an immediate to match.
12283 int64_t Value = CST->getSExtValue();
12284 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
12285 // numbers are printed as such.
12287 default: llvm_unreachable("Unknown constraint letter!");
12288 case 'I': // "I" is a signed 16-bit constant.
12289 if (isInt<16>(Value))
12290 Result = DAG.getTargetConstant(Value, dl, TCVT);
12292 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
12293 if (isShiftedUInt<16, 16>(Value))
12294 Result = DAG.getTargetConstant(Value, dl, TCVT);
12296 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
12297 if (isShiftedInt<16, 16>(Value))
12298 Result = DAG.getTargetConstant(Value, dl, TCVT);
12300 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
12301 if (isUInt<16>(Value))
12302 Result = DAG.getTargetConstant(Value, dl, TCVT);
12304 case 'M': // "M" is a constant that is greater than 31.
12306 Result = DAG.getTargetConstant(Value, dl, TCVT);
12308 case 'N': // "N" is a positive constant that is an exact power of two.
12309 if (Value > 0 && isPowerOf2_64(Value))
12310 Result = DAG.getTargetConstant(Value, dl, TCVT);
12312 case 'O': // "O" is the constant zero.
12314 Result = DAG.getTargetConstant(Value, dl, TCVT);
12316 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
12317 if (isInt<16>(-Value))
12318 Result = DAG.getTargetConstant(Value, dl, TCVT);
12325 if (Result.getNode()) {
12326 Ops.push_back(Result);
12330 // Handle standard constraint letters.
12331 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12334 // isLegalAddressingMode - Return true if the addressing mode represented
12335 // by AM is legal for this target, for a load/store of the specified type.
12336 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
12337 const AddrMode &AM, Type *Ty,
12338 unsigned AS) const {
12339 // PPC does not allow r+i addressing modes for vectors!
12340 if (Ty->isVectorTy() && AM.BaseOffs != 0)
12343 // PPC allows a sign-extended 16-bit immediate field.
12344 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
12347 // No global is ever allowed as a base.
12351 // PPC only support r+r,
12352 switch (AM.Scale) {
12353 case 0: // "r+i" or just "i", depending on HasBaseReg.
12356 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
12358 // Otherwise we have r+r or r+i.
12361 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
12363 // Allow 2*r as r+r.
12366 // No other scales are supported.
12373 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
12374 SelectionDAG &DAG) const {
12375 MachineFunction &MF = DAG.getMachineFunction();
12376 MachineFrameInfo &MFI = MF.getFrameInfo();
12377 MFI.setReturnAddressIsTaken(true);
12379 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12383 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12385 // Make sure the function does not optimize away the store of the RA to
12387 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
12388 FuncInfo->setLRStoreRequired();
12389 bool isPPC64 = Subtarget.isPPC64();
12390 auto PtrVT = getPointerTy(MF.getDataLayout());
12393 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12395 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
12396 isPPC64 ? MVT::i64 : MVT::i32);
12397 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12398 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
12399 MachinePointerInfo());
12402 // Just load the return address off the stack.
12403 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
12404 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
12405 MachinePointerInfo());
12408 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
12409 SelectionDAG &DAG) const {
12411 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12413 MachineFunction &MF = DAG.getMachineFunction();
12414 MachineFrameInfo &MFI = MF.getFrameInfo();
12415 MFI.setFrameAddressIsTaken(true);
12417 EVT PtrVT = getPointerTy(MF.getDataLayout());
12418 bool isPPC64 = PtrVT == MVT::i64;
12420 // Naked functions never have a frame pointer, and so we use r1. For all
12421 // other functions, this decision must be delayed until during PEI.
12423 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
12424 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
12426 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
12428 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
12431 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
12432 FrameAddr, MachinePointerInfo());
12436 // FIXME? Maybe this could be a TableGen attribute on some registers and
12437 // this table could be generated automatically from RegInfo.
12438 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
12439 SelectionDAG &DAG) const {
12440 bool isPPC64 = Subtarget.isPPC64();
12441 bool isDarwinABI = Subtarget.isDarwinABI();
12443 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
12444 (!isPPC64 && VT != MVT::i32))
12445 report_fatal_error("Invalid register global variable type");
12447 bool is64Bit = isPPC64 && VT == MVT::i64;
12448 unsigned Reg = StringSwitch<unsigned>(RegName)
12449 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
12450 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
12451 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
12452 (is64Bit ? PPC::X13 : PPC::R13))
12457 report_fatal_error("Invalid register name global variable");
12461 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
12462 // The PowerPC target isn't yet aware of offsets.
12466 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
12468 unsigned Intrinsic) const {
12469 switch (Intrinsic) {
12470 case Intrinsic::ppc_qpx_qvlfd:
12471 case Intrinsic::ppc_qpx_qvlfs:
12472 case Intrinsic::ppc_qpx_qvlfcd:
12473 case Intrinsic::ppc_qpx_qvlfcs:
12474 case Intrinsic::ppc_qpx_qvlfiwa:
12475 case Intrinsic::ppc_qpx_qvlfiwz:
12476 case Intrinsic::ppc_altivec_lvx:
12477 case Intrinsic::ppc_altivec_lvxl:
12478 case Intrinsic::ppc_altivec_lvebx:
12479 case Intrinsic::ppc_altivec_lvehx:
12480 case Intrinsic::ppc_altivec_lvewx:
12481 case Intrinsic::ppc_vsx_lxvd2x:
12482 case Intrinsic::ppc_vsx_lxvw4x: {
12484 switch (Intrinsic) {
12485 case Intrinsic::ppc_altivec_lvebx:
12488 case Intrinsic::ppc_altivec_lvehx:
12491 case Intrinsic::ppc_altivec_lvewx:
12494 case Intrinsic::ppc_vsx_lxvd2x:
12497 case Intrinsic::ppc_qpx_qvlfd:
12500 case Intrinsic::ppc_qpx_qvlfs:
12503 case Intrinsic::ppc_qpx_qvlfcd:
12506 case Intrinsic::ppc_qpx_qvlfcs:
12514 Info.opc = ISD::INTRINSIC_W_CHAIN;
12516 Info.ptrVal = I.getArgOperand(0);
12517 Info.offset = -VT.getStoreSize()+1;
12518 Info.size = 2*VT.getStoreSize()-1;
12521 Info.readMem = true;
12522 Info.writeMem = false;
12525 case Intrinsic::ppc_qpx_qvlfda:
12526 case Intrinsic::ppc_qpx_qvlfsa:
12527 case Intrinsic::ppc_qpx_qvlfcda:
12528 case Intrinsic::ppc_qpx_qvlfcsa:
12529 case Intrinsic::ppc_qpx_qvlfiwaa:
12530 case Intrinsic::ppc_qpx_qvlfiwza: {
12532 switch (Intrinsic) {
12533 case Intrinsic::ppc_qpx_qvlfda:
12536 case Intrinsic::ppc_qpx_qvlfsa:
12539 case Intrinsic::ppc_qpx_qvlfcda:
12542 case Intrinsic::ppc_qpx_qvlfcsa:
12550 Info.opc = ISD::INTRINSIC_W_CHAIN;
12552 Info.ptrVal = I.getArgOperand(0);
12554 Info.size = VT.getStoreSize();
12557 Info.readMem = true;
12558 Info.writeMem = false;
12561 case Intrinsic::ppc_qpx_qvstfd:
12562 case Intrinsic::ppc_qpx_qvstfs:
12563 case Intrinsic::ppc_qpx_qvstfcd:
12564 case Intrinsic::ppc_qpx_qvstfcs:
12565 case Intrinsic::ppc_qpx_qvstfiw:
12566 case Intrinsic::ppc_altivec_stvx:
12567 case Intrinsic::ppc_altivec_stvxl:
12568 case Intrinsic::ppc_altivec_stvebx:
12569 case Intrinsic::ppc_altivec_stvehx:
12570 case Intrinsic::ppc_altivec_stvewx:
12571 case Intrinsic::ppc_vsx_stxvd2x:
12572 case Intrinsic::ppc_vsx_stxvw4x: {
12574 switch (Intrinsic) {
12575 case Intrinsic::ppc_altivec_stvebx:
12578 case Intrinsic::ppc_altivec_stvehx:
12581 case Intrinsic::ppc_altivec_stvewx:
12584 case Intrinsic::ppc_vsx_stxvd2x:
12587 case Intrinsic::ppc_qpx_qvstfd:
12590 case Intrinsic::ppc_qpx_qvstfs:
12593 case Intrinsic::ppc_qpx_qvstfcd:
12596 case Intrinsic::ppc_qpx_qvstfcs:
12604 Info.opc = ISD::INTRINSIC_VOID;
12606 Info.ptrVal = I.getArgOperand(1);
12607 Info.offset = -VT.getStoreSize()+1;
12608 Info.size = 2*VT.getStoreSize()-1;
12611 Info.readMem = false;
12612 Info.writeMem = true;
12615 case Intrinsic::ppc_qpx_qvstfda:
12616 case Intrinsic::ppc_qpx_qvstfsa:
12617 case Intrinsic::ppc_qpx_qvstfcda:
12618 case Intrinsic::ppc_qpx_qvstfcsa:
12619 case Intrinsic::ppc_qpx_qvstfiwa: {
12621 switch (Intrinsic) {
12622 case Intrinsic::ppc_qpx_qvstfda:
12625 case Intrinsic::ppc_qpx_qvstfsa:
12628 case Intrinsic::ppc_qpx_qvstfcda:
12631 case Intrinsic::ppc_qpx_qvstfcsa:
12639 Info.opc = ISD::INTRINSIC_VOID;
12641 Info.ptrVal = I.getArgOperand(1);
12643 Info.size = VT.getStoreSize();
12646 Info.readMem = false;
12647 Info.writeMem = true;
12657 /// getOptimalMemOpType - Returns the target specific optimal type for load
12658 /// and store operations as a result of memset, memcpy, and memmove
12659 /// lowering. If DstAlign is zero that means it's safe to destination
12660 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
12661 /// means there isn't a need to check it against alignment requirement,
12662 /// probably because the source does not need to be loaded. If 'IsMemset' is
12663 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
12664 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
12665 /// source is constant so it does not need to be loaded.
12666 /// It returns EVT::Other if the type should be determined using generic
12667 /// target-independent logic.
12668 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
12669 unsigned DstAlign, unsigned SrcAlign,
12670 bool IsMemset, bool ZeroMemset,
12672 MachineFunction &MF) const {
12673 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
12674 const Function *F = MF.getFunction();
12675 // When expanding a memset, require at least two QPX instructions to cover
12676 // the cost of loading the value to be stored from the constant pool.
12677 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
12678 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
12679 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
12683 // We should use Altivec/VSX loads and stores when available. For unaligned
12684 // addresses, unaligned VSX loads are only fast starting with the P8.
12685 if (Subtarget.hasAltivec() && Size >= 16 &&
12686 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
12687 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
12691 if (Subtarget.isPPC64()) {
12698 /// \brief Returns true if it is beneficial to convert a load of a constant
12699 /// to just the constant itself.
12700 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
12702 assert(Ty->isIntegerTy());
12704 unsigned BitSize = Ty->getPrimitiveSizeInBits();
12705 return !(BitSize == 0 || BitSize > 64);
12708 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12709 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12711 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12712 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12713 return NumBits1 == 64 && NumBits2 == 32;
12716 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12717 if (!VT1.isInteger() || !VT2.isInteger())
12719 unsigned NumBits1 = VT1.getSizeInBits();
12720 unsigned NumBits2 = VT2.getSizeInBits();
12721 return NumBits1 == 64 && NumBits2 == 32;
12724 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12725 // Generally speaking, zexts are not free, but they are free when they can be
12726 // folded with other operations.
12727 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
12728 EVT MemVT = LD->getMemoryVT();
12729 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
12730 (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
12731 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
12732 LD->getExtensionType() == ISD::ZEXTLOAD))
12736 // FIXME: Add other cases...
12737 // - 32-bit shifts with a zext to i64
12738 // - zext after ctlz, bswap, etc.
12739 // - zext after and by a constant mask
12741 return TargetLowering::isZExtFree(Val, VT2);
12744 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
12745 assert(VT.isFloatingPoint());
12749 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12750 return isInt<16>(Imm) || isUInt<16>(Imm);
12753 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12754 return isInt<16>(Imm) || isUInt<16>(Imm);
12757 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12760 bool *Fast) const {
12761 if (DisablePPCUnaligned)
12764 // PowerPC supports unaligned memory access for simple non-vector types.
12765 // Although accessing unaligned addresses is not as efficient as accessing
12766 // aligned addresses, it is generally more efficient than manual expansion,
12767 // and generally only traps for software emulation when crossing page
12770 if (!VT.isSimple())
12773 if (VT.getSimpleVT().isVector()) {
12774 if (Subtarget.hasVSX()) {
12775 if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
12776 VT != MVT::v4f32 && VT != MVT::v4i32)
12783 if (VT == MVT::ppcf128)
12792 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
12793 VT = VT.getScalarType();
12795 if (!VT.isSimple())
12798 switch (VT.getSimpleVT().SimpleTy) {
12810 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
12811 // LR is a callee-save register, but we must treat it as clobbered by any call
12812 // site. Hence we include LR in the scratch registers, which are in turn added
12813 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
12814 // to CTR, which is used by any indirect call.
12815 static const MCPhysReg ScratchRegs[] = {
12816 PPC::X12, PPC::LR8, PPC::CTR8, 0
12819 return ScratchRegs;
12822 unsigned PPCTargetLowering::getExceptionPointerRegister(
12823 const Constant *PersonalityFn) const {
12824 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
12827 unsigned PPCTargetLowering::getExceptionSelectorRegister(
12828 const Constant *PersonalityFn) const {
12829 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
12833 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
12834 EVT VT , unsigned DefinedValues) const {
12835 if (VT == MVT::v2i64)
12836 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
12838 if (Subtarget.hasVSX() || Subtarget.hasQPX())
12841 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
12844 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
12845 if (DisableILPPref || Subtarget.enableMachineScheduler())
12846 return TargetLowering::getSchedulingPreference(N);
12851 // Create a fast isel object.
12853 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
12854 const TargetLibraryInfo *LibInfo) const {
12855 return PPC::createFastISel(FuncInfo, LibInfo);
12858 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12859 if (Subtarget.isDarwinABI()) return;
12860 if (!Subtarget.isPPC64()) return;
12862 // Update IsSplitCSR in PPCFunctionInfo
12863 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
12864 PFI->setIsSplitCSR(true);
12867 void PPCTargetLowering::insertCopiesSplitCSR(
12868 MachineBasicBlock *Entry,
12869 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12870 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
12871 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12875 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12876 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12877 MachineBasicBlock::iterator MBBI = Entry->begin();
12878 for (const MCPhysReg *I = IStart; *I; ++I) {
12879 const TargetRegisterClass *RC = nullptr;
12880 if (PPC::G8RCRegClass.contains(*I))
12881 RC = &PPC::G8RCRegClass;
12882 else if (PPC::F8RCRegClass.contains(*I))
12883 RC = &PPC::F8RCRegClass;
12884 else if (PPC::CRRCRegClass.contains(*I))
12885 RC = &PPC::CRRCRegClass;
12886 else if (PPC::VRRCRegClass.contains(*I))
12887 RC = &PPC::VRRCRegClass;
12889 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12891 unsigned NewVR = MRI->createVirtualRegister(RC);
12892 // Create copy from CSR to a virtual register.
12893 // FIXME: this currently does not emit CFI pseudo-instructions, it works
12894 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12895 // nounwind. If we want to generalize this later, we may need to emit
12896 // CFI pseudo-instructions.
12897 assert(Entry->getParent()->getFunction()->hasFnAttribute(
12898 Attribute::NoUnwind) &&
12899 "Function should be nounwind in insertCopiesSplitCSR!");
12900 Entry->addLiveIn(*I);
12901 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12904 // Insert the copy-back instructions right before the terminator
12905 for (auto *Exit : Exits)
12906 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12907 TII->get(TargetOpcode::COPY), *I)
12912 // Override to enable LOAD_STACK_GUARD lowering on Linux.
12913 bool PPCTargetLowering::useLoadStackGuardNode() const {
12914 if (!Subtarget.isTargetLinux())
12915 return TargetLowering::useLoadStackGuardNode();
12919 // Override to disable global variable loading on Linux.
12920 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
12921 if (!Subtarget.isTargetLinux())
12922 return TargetLowering::insertSSPDeclarations(M);
12925 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
12926 if (!VT.isSimple() || !Subtarget.hasVSX())
12929 switch(VT.getSimpleVT().SimpleTy) {
12931 // For FP types that are currently not supported by PPC backend, return
12932 // false. Examples: f16, f80.
12937 return Imm.isPosZero();