LLVM  8.0.0svn
PPCISelLowering.cpp
Go to the documentation of this file.
1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the PPCISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "PPCISelLowering.h"
16 #include "PPC.h"
17 #include "PPCCCState.h"
18 #include "PPCCallingConv.h"
19 #include "PPCFrameLowering.h"
20 #include "PPCInstrInfo.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/STLExtras.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/ADT/StringSwitch.h"
57 #include "llvm/IR/CallSite.h"
58 #include "llvm/IR/CallingConv.h"
59 #include "llvm/IR/Constant.h"
60 #include "llvm/IR/Constants.h"
61 #include "llvm/IR/DataLayout.h"
62 #include "llvm/IR/DebugLoc.h"
63 #include "llvm/IR/DerivedTypes.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/GlobalValue.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/Intrinsics.h"
69 #include "llvm/IR/Module.h"
70 #include "llvm/IR/Type.h"
71 #include "llvm/IR/Use.h"
72 #include "llvm/IR/Value.h"
73 #include "llvm/MC/MCExpr.h"
74 #include "llvm/MC/MCRegisterInfo.h"
77 #include "llvm/Support/Casting.h"
78 #include "llvm/Support/CodeGen.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/Debug.h"
83 #include "llvm/Support/Format.h"
84 #include "llvm/Support/KnownBits.h"
90 #include <algorithm>
91 #include <cassert>
92 #include <cstdint>
93 #include <iterator>
94 #include <list>
95 #include <utility>
96 #include <vector>
97 
98 using namespace llvm;
99 
100 #define DEBUG_TYPE "ppc-lowering"
101 
102 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
103 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
104 
105 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
106 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
107 
108 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
109 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
110 
111 static cl::opt<bool> DisableSCO("disable-ppc-sco",
112 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
113 
114 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision",
115 cl::desc("enable quad precision float support on ppc"), cl::Hidden);
116 
117 STATISTIC(NumTailCalls, "Number of tail calls");
118 STATISTIC(NumSiblingCalls, "Number of sibling calls");
119 
120 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
121 
122 // FIXME: Remove this once the bug has been fixed!
124 
126  const PPCSubtarget &STI)
127  : TargetLowering(TM), Subtarget(STI) {
128  // Use _setjmp/_longjmp instead of setjmp/longjmp.
131 
132  // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
133  // arguments are at least 4/8 bytes aligned.
134  bool isPPC64 = Subtarget.isPPC64();
135  setMinStackArgumentAlignment(isPPC64 ? 8:4);
136 
137  // Set up the register classes.
138  addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
139  if (!useSoftFloat()) {
140  if (hasSPE()) {
141  addRegisterClass(MVT::f32, &PPC::SPE4RCRegClass);
142  addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
143  } else {
144  addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
145  addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
146  }
147  }
148 
149  // Match BITREVERSE to customized fast code sequence in the td file.
152 
153  // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
155 
156  // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
157  for (MVT VT : MVT::integer_valuetypes()) {
160  }
161 
163 
164  // PowerPC has pre-inc load and store's.
175  if (!Subtarget.hasSPE()) {
180  }
181 
182  // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
183  const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
184  for (MVT VT : ScalarIntVTs) {
189  }
190 
191  if (Subtarget.useCRBits()) {
193 
194  if (isPPC64 || Subtarget.hasFPCVT()) {
197  isPPC64 ? MVT::i64 : MVT::i32);
200  isPPC64 ? MVT::i64 : MVT::i32);
201  } else {
204  }
205 
206  // PowerPC does not support direct load/store of condition registers.
209 
210  // FIXME: Remove this once the ANDI glue bug is fixed:
211  if (ANDIGlueBug)
213 
214  for (MVT VT : MVT::integer_valuetypes()) {
218  }
219 
220  addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
221  }
222 
223  // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
224  // PPC (the libcall is not available).
227 
228  // We do not currently implement these libm ops for PowerPC.
235 
236  // PowerPC has no SREM/UREM instructions unless we are on P9
237  // On P9 we may use a hardware instruction to compute the remainder.
238  // The instructions are not legalized directly because in the cases where the
239  // result of both the remainder and the division is required it is more
240  // efficient to compute the remainder from the result of the division rather
241  // than use the remainder instruction.
242  if (Subtarget.isISA3_0()) {
245  setOperationAction(ISD::SREM, MVT::i64, Custom);
246  setOperationAction(ISD::UREM, MVT::i64, Custom);
247  } else {
250  setOperationAction(ISD::SREM, MVT::i64, Expand);
251  setOperationAction(ISD::UREM, MVT::i64, Expand);
252  }
253 
254  if (Subtarget.hasP9Vector()) {
258  }
259 
260  // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
269 
270  // We don't support sin/cos/sqrt/fmod/pow
281  if (Subtarget.hasSPE()) {
284  } else {
287  }
288 
290 
291  // If we're enabling GP optimizations, use hardware square root
292  if (!Subtarget.hasFSQRT() &&
293  !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
294  Subtarget.hasFRE()))
296 
297  if (!Subtarget.hasFSQRT() &&
298  !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
299  Subtarget.hasFRES()))
301 
302  if (Subtarget.hasFCPSGN()) {
305  } else {
308  }
309 
310  if (Subtarget.hasFPRND()) {
315 
320  }
321 
322  // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
323  // to speed up scalar BSWAP64.
324  // CTPOP or CTTZ were introduced in P8/P9 respectively
326  if (Subtarget.isISA3_0()) {
327  setOperationAction(ISD::BSWAP, MVT::i64 , Custom);
329  setOperationAction(ISD::CTTZ , MVT::i64 , Legal);
330  } else {
331  setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
333  setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
334  }
335 
336  if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
338  setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
339  } else {
341  setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
342  }
343 
344  // PowerPC does not have ROTR
346  setOperationAction(ISD::ROTR, MVT::i64 , Expand);
347 
348  if (!Subtarget.useCRBits()) {
349  // PowerPC does not have Select
354  }
355 
356  // PowerPC wants to turn select_cc of FP into fsel when possible.
359 
360  // PowerPC wants to optimize integer setcc a bit
361  if (!Subtarget.useCRBits())
363 
364  // PowerPC does not have BRCOND which requires SetCC
365  if (!Subtarget.useCRBits())
367 
369 
370  if (Subtarget.hasSPE()) {
371  // SPE has built-in conversions
375  } else {
376  // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
378 
379  // PowerPC does not have [U|S]INT_TO_FP
382  }
383 
384  if (Subtarget.hasDirectMove() && isPPC64) {
389  } else {
394  }
395 
396  // We cannot sextinreg(i1). Expand to shifts.
398 
399  // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
400  // SjLj exception handling but a light-weight setjmp/longjmp replacement to
401  // support continuation, user-level threading, and etc.. As a result, no
402  // other SjLj exception interfaces are implemented and please don't build
403  // your own exception handling based on them.
404  // LLVM/Clang supports zero-cost DWARF exception handling.
407 
408  // We want to legalize GlobalAddress and ConstantPool nodes into the
409  // appropriate instructions to materialize the address.
420 
421  // TRAP is legal.
423 
424  // TRAMPOLINE is custom lowered.
427 
428  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
430 
431  if (Subtarget.isSVR4ABI()) {
432  if (isPPC64) {
433  // VAARG always uses double-word chunks, so promote anything smaller.
435  AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
437  AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
443  } else {
444  // VAARG is custom lowered with the 32-bit SVR4 ABI.
447  }
448  } else
450 
451  if (Subtarget.isSVR4ABI() && !isPPC64)
452  // VACOPY is custom lowered with the 32-bit SVR4 ABI.
454  else
456 
457  // Use the default implementation.
467 
468  // We want to custom lower some of our intrinsics.
470 
471  // To handle counter-based loop conditions.
473 
478 
479  // Comparisons that require checking two conditions.
480  if (Subtarget.hasSPE()) {
485  }
498 
499  if (Subtarget.has64BitSupport()) {
500  // They also have instructions for converting between i64 and fp.
505  // This is just the low 32 bits of a (signed) fp->i64 conversion.
506  // We cannot do this with Promote because i64 is not a legal type.
508 
509  if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
511  } else {
512  // PowerPC does not have FP_TO_UINT on 32-bit implementations.
513  if (Subtarget.hasSPE())
515  else
517  }
518 
519  // With the instructions enabled under FPCVT, we can do everything.
520  if (Subtarget.hasFPCVT()) {
521  if (Subtarget.has64BitSupport()) {
526  }
527 
532  }
533 
534  if (Subtarget.use64BitRegs()) {
535  // 64-bit PowerPC implementations can support i64 types directly
536  addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
537  // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
539  // 64-bit PowerPC wants to expand i128 shifts itself.
543  } else {
544  // 32-bit PowerPC wants to expand i64 shifts itself.
548  }
549 
550  if (Subtarget.hasAltivec()) {
551  // First set operation action for all vector types to expand. Then we
552  // will selectively turn on ones that can be effectively codegen'd.
553  for (MVT VT : MVT::vector_valuetypes()) {
554  // add/sub are legal for all supported vector VT's.
557 
558  // Vector instructions introduced in P8
559  if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
562  }
563  else {
566  }
567 
568  // Vector instructions introduced in P9
569  if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
571  else
573 
574  // We promote all shuffles to v16i8.
577 
578  // We promote all non-typed operations to v4i32.
593 
594  // No other operations are legal.
633 
634  for (MVT InnerVT : MVT::vector_valuetypes()) {
635  setTruncStoreAction(VT, InnerVT, Expand);
636  setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
637  setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
638  setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
639  }
640  }
641 
642  // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
643  // with merges, splats, etc.
645 
651  Subtarget.useCRBits() ? Legal : Expand);
661 
662  addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
663  addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
664  addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
665  addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
666 
669 
670  if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
673  }
674 
675  if (Subtarget.hasP8Altivec())
677  else
679 
682 
685 
690 
691  // Altivec does not contain unordered floating-point compare instructions
696 
697  if (Subtarget.hasVSX()) {
700  if (Subtarget.hasP8Vector()) {
703  }
704  if (Subtarget.hasDirectMove() && isPPC64) {
713  }
715 
721 
723 
726 
729 
735 
736  // Share the Altivec comparison restrictions.
741 
744 
746 
747  if (Subtarget.hasP8Vector())
748  addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
749 
750  addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
751 
752  addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
753  addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
754  addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
755 
756  if (Subtarget.hasP8Altivec()) {
760 
761  // 128 bit shifts can be accomplished via 3 instructions for SHL and
762  // SRL, but not for SRA because of the instructions available:
763  // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
764  // doing
768 
770  }
771  else {
775 
777 
778  // VSX v2i64 only supports non-arithmetic operations.
781  }
782 
787 
789 
794 
795  // Vector operation legalization checks the result type of
796  // SIGN_EXTEND_INREG, overall legalization checks the inner type.
801 
806 
807  if (Subtarget.hasDirectMove())
810 
811  addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
812  }
813 
814  if (Subtarget.hasP8Altivec()) {
815  addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
816  addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
817  }
818 
819  if (Subtarget.hasP9Vector()) {
822 
823  // 128 bit shifts can be accomplished via 3 instructions for SHL and
824  // SRL, but not for SRA because of the instructions available:
825  // VS{RL} and VS{RL}O.
829 
830  if (EnableQuadPrecision) {
831  addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
837  // No extending loads to f128 on PPC.
838  for (MVT FPT : MVT::fp_valuetypes())
847 
854 
861  // No implementation for these ops for PowerPC.
867  }
868 
869  }
870 
871  if (Subtarget.hasP9Altivec()) {
874  }
875  }
876 
877  if (Subtarget.hasQPX()) {
882 
885 
888 
891 
892  if (!Subtarget.useCRBits())
895 
903 
906 
910 
921 
924 
927 
928  addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
929 
934 
937 
940 
941  if (!Subtarget.useCRBits())
944 
952 
955 
966 
969 
972 
973  addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
974 
978 
979  if (!Subtarget.useCRBits())
982 
985 
993 
996 
997  addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
998 
1003 
1008 
1011 
1012  // These need to set FE_INEXACT, and so cannot be vectorized here.
1015 
1016  if (TM.Options.UnsafeFPMath) {
1019 
1022  } else {
1025 
1028  }
1029  }
1030 
1031  if (Subtarget.has64BitSupport())
1033 
1034  setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1035 
1036  if (!isPPC64) {
1039  }
1040 
1042 
1043  if (Subtarget.hasAltivec()) {
1044  // Altivec instructions set fields to all zeros or all ones.
1046  }
1047 
1048  if (!isPPC64) {
1049  // These libcalls are not available in 32-bit.
1050  setLibcallName(RTLIB::SHL_I128, nullptr);
1051  setLibcallName(RTLIB::SRL_I128, nullptr);
1052  setLibcallName(RTLIB::SRA_I128, nullptr);
1053  }
1054 
1055  setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1056 
1057  // We have target-specific dag combine patterns for the following nodes:
1064  if (Subtarget.hasFPCVT())
1069  if (Subtarget.useCRBits())
1075 
1079 
1080  if (Subtarget.useCRBits()) {
1084  }
1085 
1086  // Use reciprocal estimates.
1087  if (TM.Options.UnsafeFPMath) {
1090  }
1091 
1092  // Darwin long double math library functions have $LDBL128 appended.
1093  if (Subtarget.isDarwin()) {
1094  setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
1095  setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
1096  setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
1097  setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
1098  setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
1099  setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
1100  setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
1101  setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
1102  setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
1103  setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
1104  }
1105 
1106  if (EnableQuadPrecision) {
1107  setLibcallName(RTLIB::LOG_F128, "logf128");
1108  setLibcallName(RTLIB::LOG2_F128, "log2f128");
1109  setLibcallName(RTLIB::LOG10_F128, "log10f128");
1110  setLibcallName(RTLIB::EXP_F128, "expf128");
1111  setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1112  setLibcallName(RTLIB::SIN_F128, "sinf128");
1113  setLibcallName(RTLIB::COS_F128, "cosf128");
1114  setLibcallName(RTLIB::POW_F128, "powf128");
1115  setLibcallName(RTLIB::FMIN_F128, "fminf128");
1116  setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1117  setLibcallName(RTLIB::POWI_F128, "__powikf2");
1118  setLibcallName(RTLIB::REM_F128, "fmodf128");
1119  }
1120 
1121  // With 32 condition bits, we don't need to sink (and duplicate) compares
1122  // aggressively in CodeGenPrep.
1123  if (Subtarget.useCRBits()) {
1126  }
1127 
1129  if (Subtarget.isDarwin())
1131 
1132  switch (Subtarget.getDarwinDirective()) {
1133  default: break;
1134  case PPC::DIR_970:
1135  case PPC::DIR_A2:
1136  case PPC::DIR_E500:
1137  case PPC::DIR_E500mc:
1138  case PPC::DIR_E5500:
1139  case PPC::DIR_PWR4:
1140  case PPC::DIR_PWR5:
1141  case PPC::DIR_PWR5X:
1142  case PPC::DIR_PWR6:
1143  case PPC::DIR_PWR6X:
1144  case PPC::DIR_PWR7:
1145  case PPC::DIR_PWR8:
1146  case PPC::DIR_PWR9:
1149  break;
1150  }
1151 
1152  if (Subtarget.enableMachineScheduler())
1154  else
1156 
1158 
1159  // The Freescale cores do better with aggressive inlining of memcpy and
1160  // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1161  if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1162  Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1163  MaxStoresPerMemset = 32;
1165  MaxStoresPerMemcpy = 32;
1167  MaxStoresPerMemmove = 32;
1169  } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1170  // The A2 also benefits from (very) aggressive inlining of memcpy and
1171  // friends. The overhead of a the function call, even when warm, can be
1172  // over one hundred cycles.
1173  MaxStoresPerMemset = 128;
1174  MaxStoresPerMemcpy = 128;
1175  MaxStoresPerMemmove = 128;
1176  MaxLoadsPerMemcmp = 128;
1177  } else {
1178  MaxLoadsPerMemcmp = 8;
1180  }
1181 }
1182 
1183 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1184 /// the desired ByVal argument alignment.
1185 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1186  unsigned MaxMaxAlign) {
1187  if (MaxAlign == MaxMaxAlign)
1188  return;
1189  if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1190  if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1191  MaxAlign = 32;
1192  else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1193  MaxAlign = 16;
1194  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1195  unsigned EltAlign = 0;
1196  getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1197  if (EltAlign > MaxAlign)
1198  MaxAlign = EltAlign;
1199  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1200  for (auto *EltTy : STy->elements()) {
1201  unsigned EltAlign = 0;
1202  getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1203  if (EltAlign > MaxAlign)
1204  MaxAlign = EltAlign;
1205  if (MaxAlign == MaxMaxAlign)
1206  break;
1207  }
1208  }
1209 }
1210 
1211 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1212 /// function arguments in the caller parameter area.
1214  const DataLayout &DL) const {
1215  // Darwin passes everything on 4 byte boundary.
1216  if (Subtarget.isDarwin())
1217  return 4;
1218 
1219  // 16byte and wider vectors are passed on 16byte boundary.
1220  // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1221  unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1222  if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1223  getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1224  return Align;
1225 }
1226 
1228  CallingConv:: ID CC,
1229  EVT VT) const {
1230  if (Subtarget.hasSPE() && VT == MVT::f64)
1231  return 2;
1232  return PPCTargetLowering::getNumRegisters(Context, VT);
1233 }
1234 
1236  CallingConv:: ID CC,
1237  EVT VT) const {
1238  if (Subtarget.hasSPE() && VT == MVT::f64)
1239  return MVT::i32;
1240  return PPCTargetLowering::getRegisterType(Context, VT);
1241 }
1242 
1244  return Subtarget.useSoftFloat();
1245 }
1246 
1248  return Subtarget.hasSPE();
1249 }
1250 
1251 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1252  switch ((PPCISD::NodeType)Opcode) {
1253  case PPCISD::FIRST_NUMBER: break;
1254  case PPCISD::FSEL: return "PPCISD::FSEL";
1255  case PPCISD::FCFID: return "PPCISD::FCFID";
1256  case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
1257  case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
1258  case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
1259  case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
1260  case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
1261  case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
1262  case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
1264  return "PPCISD::FP_TO_UINT_IN_VSR,";
1266  return "PPCISD::FP_TO_SINT_IN_VSR";
1267  case PPCISD::FRE: return "PPCISD::FRE";
1268  case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
1269  case PPCISD::STFIWX: return "PPCISD::STFIWX";
1270  case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
1271  case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
1272  case PPCISD::VPERM: return "PPCISD::VPERM";
1273  case PPCISD::XXSPLT: return "PPCISD::XXSPLT";
1274  case PPCISD::VECINSERT: return "PPCISD::VECINSERT";
1275  case PPCISD::XXREVERSE: return "PPCISD::XXREVERSE";
1276  case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI";
1277  case PPCISD::VECSHL: return "PPCISD::VECSHL";
1278  case PPCISD::CMPB: return "PPCISD::CMPB";
1279  case PPCISD::Hi: return "PPCISD::Hi";
1280  case PPCISD::Lo: return "PPCISD::Lo";
1281  case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
1282  case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1283  case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1284  case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
1285  case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET";
1286  case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
1287  case PPCISD::SRL: return "PPCISD::SRL";
1288  case PPCISD::SRA: return "PPCISD::SRA";
1289  case PPCISD::SHL: return "PPCISD::SHL";
1290  case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE";
1291  case PPCISD::CALL: return "PPCISD::CALL";
1292  case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
1293  case PPCISD::MTCTR: return "PPCISD::MTCTR";
1294  case PPCISD::BCTRL: return "PPCISD::BCTRL";
1295  case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
1296  case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
1297  case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
1298  case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
1299  case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1300  case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
1301  case PPCISD::MFVSR: return "PPCISD::MFVSR";
1302  case PPCISD::MTVSRA: return "PPCISD::MTVSRA";
1303  case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ";
1304  case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP";
1305  case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP";
1306  case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT";
1307  case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT";
1308  case PPCISD::VCMP: return "PPCISD::VCMP";
1309  case PPCISD::VCMPo: return "PPCISD::VCMPo";
1310  case PPCISD::LBRX: return "PPCISD::LBRX";
1311  case PPCISD::STBRX: return "PPCISD::STBRX";
1312  case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
1313  case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
1314  case PPCISD::LXSIZX: return "PPCISD::LXSIZX";
1315  case PPCISD::STXSIX: return "PPCISD::STXSIX";
1316  case PPCISD::VEXTS: return "PPCISD::VEXTS";
1317  case PPCISD::SExtVElems: return "PPCISD::SExtVElems";
1318  case PPCISD::LXVD2X: return "PPCISD::LXVD2X";
1319  case PPCISD::STXVD2X: return "PPCISD::STXVD2X";
1321  return "PPCISD::ST_VSR_SCAL_INT";
1322  case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
1323  case PPCISD::BDNZ: return "PPCISD::BDNZ";
1324  case PPCISD::BDZ: return "PPCISD::BDZ";
1325  case PPCISD::MFFS: return "PPCISD::MFFS";
1326  case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
1327  case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
1328  case PPCISD::CR6SET: return "PPCISD::CR6SET";
1329  case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
1330  case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
1331  case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT";
1332  case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1333  case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
1334  case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
1335  case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
1336  case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
1337  case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
1338  case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1339  case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
1340  case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
1341  case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
1342  case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1343  case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1344  case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
1345  case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
1346  case PPCISD::SC: return "PPCISD::SC";
1347  case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB";
1348  case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE";
1349  case PPCISD::RFEBB: return "PPCISD::RFEBB";
1350  case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD";
1351  case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN";
1352  case PPCISD::QVFPERM: return "PPCISD::QVFPERM";
1353  case PPCISD::QVGPCI: return "PPCISD::QVGPCI";
1354  case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI";
1355  case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI";
1356  case PPCISD::QBFLT: return "PPCISD::QBFLT";
1357  case PPCISD::QVLFSb: return "PPCISD::QVLFSb";
1358  case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128";
1359  case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI";
1360  }
1361  return nullptr;
1362 }
1363 
1365  EVT VT) const {
1366  if (!VT.isVector())
1367  return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1368 
1369  if (Subtarget.hasQPX())
1371 
1373 }
1374 
1376  assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1377  return true;
1378 }
1379 
1380 //===----------------------------------------------------------------------===//
1381 // Node matching predicates, for use by the tblgen matching code.
1382 //===----------------------------------------------------------------------===//
1383 
1384 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1386  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1387  return CFP->getValueAPF().isZero();
1388  else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1389  // Maybe this has already been legalized into the constant pool?
1390  if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1391  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1392  return CFP->getValueAPF().isZero();
1393  }
1394  return false;
1395 }
1396 
1397 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1398 /// true if Op is undef or if it matches the specified value.
1399 static bool isConstantOrUndef(int Op, int Val) {
1400  return Op < 0 || Op == Val;
1401 }
1402 
1403 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1404 /// VPKUHUM instruction.
1405 /// The ShuffleKind distinguishes between big-endian operations with
1406 /// two different inputs (0), either-endian operations with two identical
1407 /// inputs (1), and little-endian operations with two different inputs (2).
1408 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1410  SelectionDAG &DAG) {
1411  bool IsLE = DAG.getDataLayout().isLittleEndian();
1412  if (ShuffleKind == 0) {
1413  if (IsLE)
1414  return false;
1415  for (unsigned i = 0; i != 16; ++i)
1416  if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1417  return false;
1418  } else if (ShuffleKind == 2) {
1419  if (!IsLE)
1420  return false;
1421  for (unsigned i = 0; i != 16; ++i)
1422  if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1423  return false;
1424  } else if (ShuffleKind == 1) {
1425  unsigned j = IsLE ? 0 : 1;
1426  for (unsigned i = 0; i != 8; ++i)
1427  if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1428  !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1429  return false;
1430  }
1431  return true;
1432 }
1433 
1434 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1435 /// VPKUWUM instruction.
1436 /// The ShuffleKind distinguishes between big-endian operations with
1437 /// two different inputs (0), either-endian operations with two identical
1438 /// inputs (1), and little-endian operations with two different inputs (2).
1439 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1441  SelectionDAG &DAG) {
1442  bool IsLE = DAG.getDataLayout().isLittleEndian();
1443  if (ShuffleKind == 0) {
1444  if (IsLE)
1445  return false;
1446  for (unsigned i = 0; i != 16; i += 2)
1447  if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1448  !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1449  return false;
1450  } else if (ShuffleKind == 2) {
1451  if (!IsLE)
1452  return false;
1453  for (unsigned i = 0; i != 16; i += 2)
1454  if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1455  !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1456  return false;
1457  } else if (ShuffleKind == 1) {
1458  unsigned j = IsLE ? 0 : 2;
1459  for (unsigned i = 0; i != 8; i += 2)
1460  if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1461  !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1462  !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1463  !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1464  return false;
1465  }
1466  return true;
1467 }
1468 
1469 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1470 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1471 /// current subtarget.
1472 ///
1473 /// The ShuffleKind distinguishes between big-endian operations with
1474 /// two different inputs (0), either-endian operations with two identical
1475 /// inputs (1), and little-endian operations with two different inputs (2).
1476 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1478  SelectionDAG &DAG) {
1479  const PPCSubtarget& Subtarget =
1480  static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1481  if (!Subtarget.hasP8Vector())
1482  return false;
1483 
1484  bool IsLE = DAG.getDataLayout().isLittleEndian();
1485  if (ShuffleKind == 0) {
1486  if (IsLE)
1487  return false;
1488  for (unsigned i = 0; i != 16; i += 4)
1489  if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) ||
1490  !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) ||
1491  !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) ||
1492  !isConstantOrUndef(N->getMaskElt(i+3), i*2+7))
1493  return false;
1494  } else if (ShuffleKind == 2) {
1495  if (!IsLE)
1496  return false;
1497  for (unsigned i = 0; i != 16; i += 4)
1498  if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1499  !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) ||
1500  !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) ||
1501  !isConstantOrUndef(N->getMaskElt(i+3), i*2+3))
1502  return false;
1503  } else if (ShuffleKind == 1) {
1504  unsigned j = IsLE ? 0 : 4;
1505  for (unsigned i = 0; i != 8; i += 4)
1506  if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1507  !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1508  !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) ||
1509  !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) ||
1510  !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1511  !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) ||
1512  !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1513  !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1514  return false;
1515  }
1516  return true;
1517 }
1518 
1519 /// isVMerge - Common function, used to match vmrg* shuffles.
1520 ///
1521 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1522  unsigned LHSStart, unsigned RHSStart) {
1523  if (N->getValueType(0) != MVT::v16i8)
1524  return false;
1525  assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1526  "Unsupported merge size!");
1527 
1528  for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
1529  for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
1530  if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1531  LHSStart+j+i*UnitSize) ||
1532  !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1533  RHSStart+j+i*UnitSize))
1534  return false;
1535  }
1536  return true;
1537 }
1538 
1539 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1540 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1541 /// The ShuffleKind distinguishes between big-endian merges with two
1542 /// different inputs (0), either-endian merges with two identical inputs (1),
1543 /// and little-endian merges with two different inputs (2). For the latter,
1544 /// the input operands are swapped (see PPCInstrAltivec.td).
1546  unsigned ShuffleKind, SelectionDAG &DAG) {
1547  if (DAG.getDataLayout().isLittleEndian()) {
1548  if (ShuffleKind == 1) // unary
1549  return isVMerge(N, UnitSize, 0, 0);
1550  else if (ShuffleKind == 2) // swapped
1551  return isVMerge(N, UnitSize, 0, 16);
1552  else
1553  return false;
1554  } else {
1555  if (ShuffleKind == 1) // unary
1556  return isVMerge(N, UnitSize, 8, 8);
1557  else if (ShuffleKind == 0) // normal
1558  return isVMerge(N, UnitSize, 8, 24);
1559  else
1560  return false;
1561  }
1562 }
1563 
1564 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1565 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1566 /// The ShuffleKind distinguishes between big-endian merges with two
1567 /// different inputs (0), either-endian merges with two identical inputs (1),
1568 /// and little-endian merges with two different inputs (2). For the latter,
1569 /// the input operands are swapped (see PPCInstrAltivec.td).
1571  unsigned ShuffleKind, SelectionDAG &DAG) {
1572  if (DAG.getDataLayout().isLittleEndian()) {
1573  if (ShuffleKind == 1) // unary
1574  return isVMerge(N, UnitSize, 8, 8);
1575  else if (ShuffleKind == 2) // swapped
1576  return isVMerge(N, UnitSize, 8, 24);
1577  else
1578  return false;
1579  } else {
1580  if (ShuffleKind == 1) // unary
1581  return isVMerge(N, UnitSize, 0, 0);
1582  else if (ShuffleKind == 0) // normal
1583  return isVMerge(N, UnitSize, 0, 16);
1584  else
1585  return false;
1586  }
1587 }
1588 
1589 /**
1590  * Common function used to match vmrgew and vmrgow shuffles
1591  *
1592  * The indexOffset determines whether to look for even or odd words in
1593  * the shuffle mask. This is based on the of the endianness of the target
1594  * machine.
1595  * - Little Endian:
1596  * - Use offset of 0 to check for odd elements
1597  * - Use offset of 4 to check for even elements
1598  * - Big Endian:
1599  * - Use offset of 0 to check for even elements
1600  * - Use offset of 4 to check for odd elements
1601  * A detailed description of the vector element ordering for little endian and
1602  * big endian can be found at
1603  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1604  * Targeting your applications - what little endian and big endian IBM XL C/C++
1605  * compiler differences mean to you
1606  *
1607  * The mask to the shuffle vector instruction specifies the indices of the
1608  * elements from the two input vectors to place in the result. The elements are
1609  * numbered in array-access order, starting with the first vector. These vectors
1610  * are always of type v16i8, thus each vector will contain 16 elements of size
1611  * 8. More info on the shuffle vector can be found in the
1612  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1613  * Language Reference.
1614  *
1615  * The RHSStartValue indicates whether the same input vectors are used (unary)
1616  * or two different input vectors are used, based on the following:
1617  * - If the instruction uses the same vector for both inputs, the range of the
1618  * indices will be 0 to 15. In this case, the RHSStart value passed should
1619  * be 0.
1620  * - If the instruction has two different vectors then the range of the
1621  * indices will be 0 to 31. In this case, the RHSStart value passed should
1622  * be 16 (indices 0-15 specify elements in the first vector while indices 16
1623  * to 31 specify elements in the second vector).
1624  *
1625  * \param[in] N The shuffle vector SD Node to analyze
1626  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1627  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1628  * vector to the shuffle_vector instruction
1629  * \return true iff this shuffle vector represents an even or odd word merge
1630  */
1631 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1632  unsigned RHSStartValue) {
1633  if (N->getValueType(0) != MVT::v16i8)
1634  return false;
1635 
1636  for (unsigned i = 0; i < 2; ++i)
1637  for (unsigned j = 0; j < 4; ++j)
1638  if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1639  i*RHSStartValue+j+IndexOffset) ||
1640  !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1641  i*RHSStartValue+j+IndexOffset+8))
1642  return false;
1643  return true;
1644 }
1645 
1646 /**
1647  * Determine if the specified shuffle mask is suitable for the vmrgew or
1648  * vmrgow instructions.
1649  *
1650  * \param[in] N The shuffle vector SD Node to analyze
1651  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1652  * \param[in] ShuffleKind Identify the type of merge:
1653  * - 0 = big-endian merge with two different inputs;
1654  * - 1 = either-endian merge with two identical inputs;
1655  * - 2 = little-endian merge with two different inputs (inputs are swapped for
1656  * little-endian merges).
1657  * \param[in] DAG The current SelectionDAG
1658  * \return true iff this shuffle mask
1659  */
1661  unsigned ShuffleKind, SelectionDAG &DAG) {
1662  if (DAG.getDataLayout().isLittleEndian()) {
1663  unsigned indexOffset = CheckEven ? 4 : 0;
1664  if (ShuffleKind == 1) // Unary
1665  return isVMerge(N, indexOffset, 0);
1666  else if (ShuffleKind == 2) // swapped
1667  return isVMerge(N, indexOffset, 16);
1668  else
1669  return false;
1670  }
1671  else {
1672  unsigned indexOffset = CheckEven ? 0 : 4;
1673  if (ShuffleKind == 1) // Unary
1674  return isVMerge(N, indexOffset, 0);
1675  else if (ShuffleKind == 0) // Normal
1676  return isVMerge(N, indexOffset, 16);
1677  else
1678  return false;
1679  }
1680  return false;
1681 }
1682 
1683 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1684 /// amount, otherwise return -1.
1685 /// The ShuffleKind distinguishes between big-endian operations with two
1686 /// different inputs (0), either-endian operations with two identical inputs
1687 /// (1), and little-endian operations with two different inputs (2). For the
1688 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1689 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1690  SelectionDAG &DAG) {
1691  if (N->getValueType(0) != MVT::v16i8)
1692  return -1;
1693 
1694  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1695 
1696  // Find the first non-undef value in the shuffle mask.
1697  unsigned i;
1698  for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1699  /*search*/;
1700 
1701  if (i == 16) return -1; // all undef.
1702 
1703  // Otherwise, check to see if the rest of the elements are consecutively
1704  // numbered from this value.
1705  unsigned ShiftAmt = SVOp->getMaskElt(i);
1706  if (ShiftAmt < i) return -1;
1707 
1708  ShiftAmt -= i;
1709  bool isLE = DAG.getDataLayout().isLittleEndian();
1710 
1711  if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1712  // Check the rest of the elements to see if they are consecutive.
1713  for (++i; i != 16; ++i)
1714  if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1715  return -1;
1716  } else if (ShuffleKind == 1) {
1717  // Check the rest of the elements to see if they are consecutive.
1718  for (++i; i != 16; ++i)
1719  if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1720  return -1;
1721  } else
1722  return -1;
1723 
1724  if (isLE)
1725  ShiftAmt = 16 - ShiftAmt;
1726 
1727  return ShiftAmt;
1728 }
1729 
1730 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1731 /// specifies a splat of a single element that is suitable for input to
1732 /// VSPLTB/VSPLTH/VSPLTW.
1734  assert(N->getValueType(0) == MVT::v16i8 &&
1735  (EltSize == 1 || EltSize == 2 || EltSize == 4));
1736 
1737  // The consecutive indices need to specify an element, not part of two
1738  // different elements. So abandon ship early if this isn't the case.
1739  if (N->getMaskElt(0) % EltSize != 0)
1740  return false;
1741 
1742  // This is a splat operation if each element of the permute is the same, and
1743  // if the value doesn't reference the second vector.
1744  unsigned ElementBase = N->getMaskElt(0);
1745 
1746  // FIXME: Handle UNDEF elements too!
1747  if (ElementBase >= 16)
1748  return false;
1749 
1750  // Check that the indices are consecutive, in the case of a multi-byte element
1751  // splatted with a v16i8 mask.
1752  for (unsigned i = 1; i != EltSize; ++i)
1753  if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1754  return false;
1755 
1756  for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1757  if (N->getMaskElt(i) < 0) continue;
1758  for (unsigned j = 0; j != EltSize; ++j)
1759  if (N->getMaskElt(i+j) != N->getMaskElt(j))
1760  return false;
1761  }
1762  return true;
1763 }
1764 
1765 /// Check that the mask is shuffling N byte elements. Within each N byte
1766 /// element of the mask, the indices could be either in increasing or
1767 /// decreasing order as long as they are consecutive.
1768 /// \param[in] N the shuffle vector SD Node to analyze
1769 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1770 /// Word/DoubleWord/QuadWord).
1771 /// \param[in] StepLen the delta indices number among the N byte element, if
1772 /// the mask is in increasing/decreasing order then it is 1/-1.
1773 /// \return true iff the mask is shuffling N byte elements.
1774 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1775  int StepLen) {
1776  assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1777  "Unexpected element width.");
1778  assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1779 
1780  unsigned NumOfElem = 16 / Width;
1781  unsigned MaskVal[16]; // Width is never greater than 16
1782  for (unsigned i = 0; i < NumOfElem; ++i) {
1783  MaskVal[0] = N->getMaskElt(i * Width);
1784  if ((StepLen == 1) && (MaskVal[0] % Width)) {
1785  return false;
1786  } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1787  return false;
1788  }
1789 
1790  for (unsigned int j = 1; j < Width; ++j) {
1791  MaskVal[j] = N->getMaskElt(i * Width + j);
1792  if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1793  return false;
1794  }
1795  }
1796  }
1797 
1798  return true;
1799 }
1800 
1801 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1802  unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1803  if (!isNByteElemShuffleMask(N, 4, 1))
1804  return false;
1805 
1806  // Now we look at mask elements 0,4,8,12
1807  unsigned M0 = N->getMaskElt(0) / 4;
1808  unsigned M1 = N->getMaskElt(4) / 4;
1809  unsigned M2 = N->getMaskElt(8) / 4;
1810  unsigned M3 = N->getMaskElt(12) / 4;
1811  unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1812  unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1813 
1814  // Below, let H and L be arbitrary elements of the shuffle mask
1815  // where H is in the range [4,7] and L is in the range [0,3].
1816  // H, 1, 2, 3 or L, 5, 6, 7
1817  if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1818  (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1819  ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1820  InsertAtByte = IsLE ? 12 : 0;
1821  Swap = M0 < 4;
1822  return true;
1823  }
1824  // 0, H, 2, 3 or 4, L, 6, 7
1825  if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1826  (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1827  ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1828  InsertAtByte = IsLE ? 8 : 4;
1829  Swap = M1 < 4;
1830  return true;
1831  }
1832  // 0, 1, H, 3 or 4, 5, L, 7
1833  if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1834  (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1835  ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1836  InsertAtByte = IsLE ? 4 : 8;
1837  Swap = M2 < 4;
1838  return true;
1839  }
1840  // 0, 1, 2, H or 4, 5, 6, L
1841  if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1842  (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1843  ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1844  InsertAtByte = IsLE ? 0 : 12;
1845  Swap = M3 < 4;
1846  return true;
1847  }
1848 
1849  // If both vector operands for the shuffle are the same vector, the mask will
1850  // contain only elements from the first one and the second one will be undef.
1851  if (N->getOperand(1).isUndef()) {
1852  ShiftElts = 0;
1853  Swap = true;
1854  unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1855  if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1856  InsertAtByte = IsLE ? 12 : 0;
1857  return true;
1858  }
1859  if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1860  InsertAtByte = IsLE ? 8 : 4;
1861  return true;
1862  }
1863  if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1864  InsertAtByte = IsLE ? 4 : 8;
1865  return true;
1866  }
1867  if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1868  InsertAtByte = IsLE ? 0 : 12;
1869  return true;
1870  }
1871  }
1872 
1873  return false;
1874 }
1875 
1877  bool &Swap, bool IsLE) {
1878  assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1879  // Ensure each byte index of the word is consecutive.
1880  if (!isNByteElemShuffleMask(N, 4, 1))
1881  return false;
1882 
1883  // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1884  unsigned M0 = N->getMaskElt(0) / 4;
1885  unsigned M1 = N->getMaskElt(4) / 4;
1886  unsigned M2 = N->getMaskElt(8) / 4;
1887  unsigned M3 = N->getMaskElt(12) / 4;
1888 
1889  // If both vector operands for the shuffle are the same vector, the mask will
1890  // contain only elements from the first one and the second one will be undef.
1891  if (N->getOperand(1).isUndef()) {
1892  assert(M0 < 4 && "Indexing into an undef vector?");
1893  if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1894  return false;
1895 
1896  ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1897  Swap = false;
1898  return true;
1899  }
1900 
1901  // Ensure each word index of the ShuffleVector Mask is consecutive.
1902  if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1903  return false;
1904 
1905  if (IsLE) {
1906  if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1907  // Input vectors don't need to be swapped if the leading element
1908  // of the result is one of the 3 left elements of the second vector
1909  // (or if there is no shift to be done at all).
1910  Swap = false;
1911  ShiftElts = (8 - M0) % 8;
1912  } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
1913  // Input vectors need to be swapped if the leading element
1914  // of the result is one of the 3 left elements of the first vector
1915  // (or if we're shifting by 4 - thereby simply swapping the vectors).
1916  Swap = true;
1917  ShiftElts = (4 - M0) % 4;
1918  }
1919 
1920  return true;
1921  } else { // BE
1922  if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
1923  // Input vectors don't need to be swapped if the leading element
1924  // of the result is one of the 4 elements of the first vector.
1925  Swap = false;
1926  ShiftElts = M0;
1927  } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
1928  // Input vectors need to be swapped if the leading element
1929  // of the result is one of the 4 elements of the right vector.
1930  Swap = true;
1931  ShiftElts = M0 - 4;
1932  }
1933 
1934  return true;
1935  }
1936 }
1937 
1939  assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1940 
1941  if (!isNByteElemShuffleMask(N, Width, -1))
1942  return false;
1943 
1944  for (int i = 0; i < 16; i += Width)
1945  if (N->getMaskElt(i) != i + Width - 1)
1946  return false;
1947 
1948  return true;
1949 }
1950 
1952  return isXXBRShuffleMaskHelper(N, 2);
1953 }
1954 
1956  return isXXBRShuffleMaskHelper(N, 4);
1957 }
1958 
1960  return isXXBRShuffleMaskHelper(N, 8);
1961 }
1962 
1964  return isXXBRShuffleMaskHelper(N, 16);
1965 }
1966 
1967 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
1968 /// if the inputs to the instruction should be swapped and set \p DM to the
1969 /// value for the immediate.
1970 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
1971 /// AND element 0 of the result comes from the first input (LE) or second input
1972 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
1973 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
1974 /// mask.
1976  bool &Swap, bool IsLE) {
1977  assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1978 
1979  // Ensure each byte index of the double word is consecutive.
1980  if (!isNByteElemShuffleMask(N, 8, 1))
1981  return false;
1982 
1983  unsigned M0 = N->getMaskElt(0) / 8;
1984  unsigned M1 = N->getMaskElt(8) / 8;
1985  assert(((M0 | M1) < 4) && "A mask element out of bounds?");
1986 
1987  // If both vector operands for the shuffle are the same vector, the mask will
1988  // contain only elements from the first one and the second one will be undef.
1989  if (N->getOperand(1).isUndef()) {
1990  if ((M0 | M1) < 2) {
1991  DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
1992  Swap = false;
1993  return true;
1994  } else
1995  return false;
1996  }
1997 
1998  if (IsLE) {
1999  if (M0 > 1 && M1 < 2) {
2000  Swap = false;
2001  } else if (M0 < 2 && M1 > 1) {
2002  M0 = (M0 + 2) % 4;
2003  M1 = (M1 + 2) % 4;
2004  Swap = true;
2005  } else
2006  return false;
2007 
2008  // Note: if control flow comes here that means Swap is already set above
2009  DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2010  return true;
2011  } else { // BE
2012  if (M0 < 2 && M1 > 1) {
2013  Swap = false;
2014  } else if (M0 > 1 && M1 < 2) {
2015  M0 = (M0 + 2) % 4;
2016  M1 = (M1 + 2) % 4;
2017  Swap = true;
2018  } else
2019  return false;
2020 
2021  // Note: if control flow comes here that means Swap is already set above
2022  DM = (M0 << 1) + (M1 & 1);
2023  return true;
2024  }
2025 }
2026 
2027 
2028 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
2029 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
2030 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
2031  SelectionDAG &DAG) {
2032  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2033  assert(isSplatShuffleMask(SVOp, EltSize));
2034  if (DAG.getDataLayout().isLittleEndian())
2035  return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2036  else
2037  return SVOp->getMaskElt(0) / EltSize;
2038 }
2039 
2040 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2041 /// by using a vspltis[bhw] instruction of the specified element size, return
2042 /// the constant being splatted. The ByteSize field indicates the number of
2043 /// bytes of each element [124] -> [bhw].
2044 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2045  SDValue OpVal(nullptr, 0);
2046 
2047  // If ByteSize of the splat is bigger than the element size of the
2048  // build_vector, then we have a case where we are checking for a splat where
2049  // multiple elements of the buildvector are folded together into a single
2050  // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2051  unsigned EltSize = 16/N->getNumOperands();
2052  if (EltSize < ByteSize) {
2053  unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
2054  SDValue UniquedVals[4];
2055  assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2056 
2057  // See if all of the elements in the buildvector agree across.
2058  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2059  if (N->getOperand(i).isUndef()) continue;
2060  // If the element isn't a constant, bail fully out.
2061  if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2062 
2063  if (!UniquedVals[i&(Multiple-1)].getNode())
2064  UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2065  else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2066  return SDValue(); // no match.
2067  }
2068 
2069  // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2070  // either constant or undef values that are identical for each chunk. See
2071  // if these chunks can form into a larger vspltis*.
2072 
2073  // Check to see if all of the leading entries are either 0 or -1. If
2074  // neither, then this won't fit into the immediate field.
2075  bool LeadingZero = true;
2076  bool LeadingOnes = true;
2077  for (unsigned i = 0; i != Multiple-1; ++i) {
2078  if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
2079 
2080  LeadingZero &= isNullConstant(UniquedVals[i]);
2081  LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2082  }
2083  // Finally, check the least significant entry.
2084  if (LeadingZero) {
2085  if (!UniquedVals[Multiple-1].getNode())
2086  return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
2087  int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2088  if (Val < 16) // 0,0,0,4 -> vspltisw(4)
2089  return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2090  }
2091  if (LeadingOnes) {
2092  if (!UniquedVals[Multiple-1].getNode())
2093  return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2094  int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2095  if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
2096  return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2097  }
2098 
2099  return SDValue();
2100  }
2101 
2102  // Check to see if this buildvec has a single non-undef value in its elements.
2103  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2104  if (N->getOperand(i).isUndef()) continue;
2105  if (!OpVal.getNode())
2106  OpVal = N->getOperand(i);
2107  else if (OpVal != N->getOperand(i))
2108  return SDValue();
2109  }
2110 
2111  if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
2112 
2113  unsigned ValSizeInBytes = EltSize;
2114  uint64_t Value = 0;
2115  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2116  Value = CN->getZExtValue();
2117  } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2118  assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2119  Value = FloatToBits(CN->getValueAPF().convertToFloat());
2120  }
2121 
2122  // If the splat value is larger than the element value, then we can never do
2123  // this splat. The only case that we could fit the replicated bits into our
2124  // immediate field for would be zero, and we prefer to use vxor for it.
2125  if (ValSizeInBytes < ByteSize) return SDValue();
2126 
2127  // If the element value is larger than the splat value, check if it consists
2128  // of a repeated bit pattern of size ByteSize.
2129  if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2130  return SDValue();
2131 
2132  // Properly sign extend the value.
2133  int MaskVal = SignExtend32(Value, ByteSize * 8);
2134 
2135  // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2136  if (MaskVal == 0) return SDValue();
2137 
2138  // Finally, if this value fits in a 5 bit sext field, return it
2139  if (SignExtend32<5>(MaskVal) == MaskVal)
2140  return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2141  return SDValue();
2142 }
2143 
2144 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2145 /// amount, otherwise return -1.
2147  EVT VT = N->getValueType(0);
2148  if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2149  return -1;
2150 
2151  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2152 
2153  // Find the first non-undef value in the shuffle mask.
2154  unsigned i;
2155  for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2156  /*search*/;
2157 
2158  if (i == 4) return -1; // all undef.
2159 
2160  // Otherwise, check to see if the rest of the elements are consecutively
2161  // numbered from this value.
2162  unsigned ShiftAmt = SVOp->getMaskElt(i);
2163  if (ShiftAmt < i) return -1;
2164  ShiftAmt -= i;
2165 
2166  // Check the rest of the elements to see if they are consecutive.
2167  for (++i; i != 4; ++i)
2168  if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2169  return -1;
2170 
2171  return ShiftAmt;
2172 }
2173 
2174 //===----------------------------------------------------------------------===//
2175 // Addressing Mode Selection
2176 //===----------------------------------------------------------------------===//
2177 
2178 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2179 /// or 64-bit immediate, and if the value can be accurately represented as a
2180 /// sign extension from a 16-bit value. If so, this returns true and the
2181 /// immediate.
2182 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2183  if (!isa<ConstantSDNode>(N))
2184  return false;
2185 
2186  Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2187  if (N->getValueType(0) == MVT::i32)
2188  return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2189  else
2190  return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2191 }
2192 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2193  return isIntS16Immediate(Op.getNode(), Imm);
2194 }
2195 
2196 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2197 /// can be represented as an indexed [r+r] operation. Returns false if it
2198 /// can be more efficiently represented with [r+imm].
2200  SDValue &Index,
2201  SelectionDAG &DAG) const {
2202  int16_t imm = 0;
2203  if (N.getOpcode() == ISD::ADD) {
2204  if (isIntS16Immediate(N.getOperand(1), imm))
2205  return false; // r+i
2206  if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2207  return false; // r+i
2208 
2209  Base = N.getOperand(0);
2210  Index = N.getOperand(1);
2211  return true;
2212  } else if (N.getOpcode() == ISD::OR) {
2213  if (isIntS16Immediate(N.getOperand(1), imm))
2214  return false; // r+i can fold it if we can.
2215 
2216  // If this is an or of disjoint bitfields, we can codegen this as an add
2217  // (for better address arithmetic) if the LHS and RHS of the OR are provably
2218  // disjoint.
2219  KnownBits LHSKnown, RHSKnown;
2220  DAG.computeKnownBits(N.getOperand(0), LHSKnown);
2221 
2222  if (LHSKnown.Zero.getBoolValue()) {
2223  DAG.computeKnownBits(N.getOperand(1), RHSKnown);
2224  // If all of the bits are known zero on the LHS or RHS, the add won't
2225  // carry.
2226  if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2227  Base = N.getOperand(0);
2228  Index = N.getOperand(1);
2229  return true;
2230  }
2231  }
2232  }
2233 
2234  return false;
2235 }
2236 
2237 // If we happen to be doing an i64 load or store into a stack slot that has
2238 // less than a 4-byte alignment, then the frame-index elimination may need to
2239 // use an indexed load or store instruction (because the offset may not be a
2240 // multiple of 4). The extra register needed to hold the offset comes from the
2241 // register scavenger, and it is possible that the scavenger will need to use
2242 // an emergency spill slot. As a result, we need to make sure that a spill slot
2243 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2244 // stack slot.
2245 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2246  // FIXME: This does not handle the LWA case.
2247  if (VT != MVT::i64)
2248  return;
2249 
2250  // NOTE: We'll exclude negative FIs here, which come from argument
2251  // lowering, because there are no known test cases triggering this problem
2252  // using packed structures (or similar). We can remove this exclusion if
2253  // we find such a test case. The reason why this is so test-case driven is
2254  // because this entire 'fixup' is only to prevent crashes (from the
2255  // register scavenger) on not-really-valid inputs. For example, if we have:
2256  // %a = alloca i1
2257  // %b = bitcast i1* %a to i64*
2258  // store i64* a, i64 b
2259  // then the store should really be marked as 'align 1', but is not. If it
2260  // were marked as 'align 1' then the indexed form would have been
2261  // instruction-selected initially, and the problem this 'fixup' is preventing
2262  // won't happen regardless.
2263  if (FrameIdx < 0)
2264  return;
2265 
2266  MachineFunction &MF = DAG.getMachineFunction();
2267  MachineFrameInfo &MFI = MF.getFrameInfo();
2268 
2269  unsigned Align = MFI.getObjectAlignment(FrameIdx);
2270  if (Align >= 4)
2271  return;
2272 
2273  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2274  FuncInfo->setHasNonRISpills();
2275 }
2276 
2277 /// Returns true if the address N can be represented by a base register plus
2278 /// a signed 16-bit displacement [r+imm], and if it is not better
2279 /// represented as reg+reg. If \p Alignment is non-zero, only accept
2280 /// displacements that are multiples of that value.
2282  SDValue &Base,
2283  SelectionDAG &DAG,
2284  unsigned Alignment) const {
2285  // FIXME dl should come from parent load or store, not from address
2286  SDLoc dl(N);
2287  // If this can be more profitably realized as r+r, fail.
2288  if (SelectAddressRegReg(N, Disp, Base, DAG))
2289  return false;
2290 
2291  if (N.getOpcode() == ISD::ADD) {
2292  int16_t imm = 0;
2293  if (isIntS16Immediate(N.getOperand(1), imm) &&
2294  (!Alignment || (imm % Alignment) == 0)) {
2295  Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2296  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2297  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2298  fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2299  } else {
2300  Base = N.getOperand(0);
2301  }
2302  return true; // [r+i]
2303  } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2304  // Match LOAD (ADD (X, Lo(G))).
2305  assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2306  && "Cannot handle constant offsets yet!");
2307  Disp = N.getOperand(1).getOperand(0); // The global address.
2308  assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2309  Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2310  Disp.getOpcode() == ISD::TargetConstantPool ||
2311  Disp.getOpcode() == ISD::TargetJumpTable);
2312  Base = N.getOperand(0);
2313  return true; // [&g+r]
2314  }
2315  } else if (N.getOpcode() == ISD::OR) {
2316  int16_t imm = 0;
2317  if (isIntS16Immediate(N.getOperand(1), imm) &&
2318  (!Alignment || (imm % Alignment) == 0)) {
2319  // If this is an or of disjoint bitfields, we can codegen this as an add
2320  // (for better address arithmetic) if the LHS and RHS of the OR are
2321  // provably disjoint.
2322  KnownBits LHSKnown;
2323  DAG.computeKnownBits(N.getOperand(0), LHSKnown);
2324 
2325  if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2326  // If all of the bits are known zero on the LHS or RHS, the add won't
2327  // carry.
2328  if (FrameIndexSDNode *FI =
2329  dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2330  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2331  fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2332  } else {
2333  Base = N.getOperand(0);
2334  }
2335  Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2336  return true;
2337  }
2338  }
2339  } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2340  // Loading from a constant address.
2341 
2342  // If this address fits entirely in a 16-bit sext immediate field, codegen
2343  // this as "d, 0"
2344  int16_t Imm;
2345  if (isIntS16Immediate(CN, Imm) && (!Alignment || (Imm % Alignment) == 0)) {
2346  Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2347  Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2348  CN->getValueType(0));
2349  return true;
2350  }
2351 
2352  // Handle 32-bit sext immediates with LIS + addr mode.
2353  if ((CN->getValueType(0) == MVT::i32 ||
2354  (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2355  (!Alignment || (CN->getZExtValue() % Alignment) == 0)) {
2356  int Addr = (int)CN->getZExtValue();
2357 
2358  // Otherwise, break this down into an LIS + disp.
2359  Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2360 
2361  Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2362  MVT::i32);
2363  unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2364  Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2365  return true;
2366  }
2367  }
2368 
2369  Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2370  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2371  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2372  fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2373  } else
2374  Base = N;
2375  return true; // [r+0]
2376 }
2377 
2378 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2379 /// represented as an indexed [r+r] operation.
2381  SDValue &Index,
2382  SelectionDAG &DAG) const {
2383  // Check to see if we can easily represent this as an [r+r] address. This
2384  // will fail if it thinks that the address is more profitably represented as
2385  // reg+imm, e.g. where imm = 0.
2386  if (SelectAddressRegReg(N, Base, Index, DAG))
2387  return true;
2388 
2389  // If the address is the result of an add, we will utilize the fact that the
2390  // address calculation includes an implicit add. However, we can reduce
2391  // register pressure if we do not materialize a constant just for use as the
2392  // index register. We only get rid of the add if it is not an add of a
2393  // value and a 16-bit signed constant and both have a single use.
2394  int16_t imm = 0;
2395  if (N.getOpcode() == ISD::ADD &&
2396  (!isIntS16Immediate(N.getOperand(1), imm) ||
2397  !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2398  Base = N.getOperand(0);
2399  Index = N.getOperand(1);
2400  return true;
2401  }
2402 
2403  // Otherwise, do it the hard way, using R0 as the base register.
2404  Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2405  N.getValueType());
2406  Index = N;
2407  return true;
2408 }
2409 
2410 /// Returns true if we should use a direct load into vector instruction
2411 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2413  if (!N->hasOneUse())
2414  return false;
2415 
2416  // If there are any other uses other than scalar to vector, then we should
2417  // keep it as a scalar load -> direct move pattern to prevent multiple
2418  // loads. Currently, only check for i64 since we have lxsd/lfd to do this
2419  // efficiently, but no update equivalent.
2420  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2421  EVT MemVT = LD->getMemoryVT();
2422  if (MemVT.isSimple() && MemVT.getSimpleVT().SimpleTy == MVT::i64) {
2423  SDNode *User = *(LD->use_begin());
2424  if (User->getOpcode() == ISD::SCALAR_TO_VECTOR)
2425  return true;
2426  }
2427  }
2428 
2429  return false;
2430 }
2431 
2432 /// getPreIndexedAddressParts - returns true by value, base pointer and
2433 /// offset pointer and addressing mode by reference if the node's address
2434 /// can be legally represented as pre-indexed load / store address.
2436  SDValue &Offset,
2437  ISD::MemIndexedMode &AM,
2438  SelectionDAG &DAG) const {
2439  if (DisablePPCPreinc) return false;
2440 
2441  bool isLoad = true;
2442  SDValue Ptr;
2443  EVT VT;
2444  unsigned Alignment;
2445  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2446  Ptr = LD->getBasePtr();
2447  VT = LD->getMemoryVT();
2448  Alignment = LD->getAlignment();
2449  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2450  Ptr = ST->getBasePtr();
2451  VT = ST->getMemoryVT();
2452  Alignment = ST->getAlignment();
2453  isLoad = false;
2454  } else
2455  return false;
2456 
2457  // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2458  // instructions because we can fold these into a more efficient instruction
2459  // instead, (such as LXSD).
2460  if (isLoad && usePartialVectorLoads(N)) {
2461  return false;
2462  }
2463 
2464  // PowerPC doesn't have preinc load/store instructions for vectors (except
2465  // for QPX, which does have preinc r+r forms).
2466  if (VT.isVector()) {
2467  if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2468  return false;
2469  } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2470  AM = ISD::PRE_INC;
2471  return true;
2472  }
2473  }
2474 
2475  if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2476  // Common code will reject creating a pre-inc form if the base pointer
2477  // is a frame index, or if N is a store and the base pointer is either
2478  // the same as or a predecessor of the value being stored. Check for
2479  // those situations here, and try with swapped Base/Offset instead.
2480  bool Swap = false;
2481 
2482  if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2483  Swap = true;
2484  else if (!isLoad) {
2485  SDValue Val = cast<StoreSDNode>(N)->getValue();
2486  if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2487  Swap = true;
2488  }
2489 
2490  if (Swap)
2491  std::swap(Base, Offset);
2492 
2493  AM = ISD::PRE_INC;
2494  return true;
2495  }
2496 
2497  // LDU/STU can only handle immediates that are a multiple of 4.
2498  if (VT != MVT::i64) {
2499  if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2500  return false;
2501  } else {
2502  // LDU/STU need an address with at least 4-byte alignment.
2503  if (Alignment < 4)
2504  return false;
2505 
2506  if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2507  return false;
2508  }
2509 
2510  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2511  // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
2512  // sext i32 to i64 when addr mode is r+i.
2513  if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2514  LD->getExtensionType() == ISD::SEXTLOAD &&
2515  isa<ConstantSDNode>(Offset))
2516  return false;
2517  }
2518 
2519  AM = ISD::PRE_INC;
2520  return true;
2521 }
2522 
2523 //===----------------------------------------------------------------------===//
2524 // LowerOperation implementation
2525 //===----------------------------------------------------------------------===//
2526 
2527 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2528 /// and LoOpFlags to the target MO flags.
2529 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2530  unsigned &HiOpFlags, unsigned &LoOpFlags,
2531  const GlobalValue *GV = nullptr) {
2532  HiOpFlags = PPCII::MO_HA;
2533  LoOpFlags = PPCII::MO_LO;
2534 
2535  // Don't use the pic base if not in PIC relocation model.
2536  if (IsPIC) {
2537  HiOpFlags |= PPCII::MO_PIC_FLAG;
2538  LoOpFlags |= PPCII::MO_PIC_FLAG;
2539  }
2540 
2541  // If this is a reference to a global value that requires a non-lazy-ptr, make
2542  // sure that instruction lowering adds it.
2543  if (GV && Subtarget.hasLazyResolverStub(GV)) {
2544  HiOpFlags |= PPCII::MO_NLP_FLAG;
2545  LoOpFlags |= PPCII::MO_NLP_FLAG;
2546 
2547  if (GV->hasHiddenVisibility()) {
2548  HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2549  LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2550  }
2551  }
2552 }
2553 
2554 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2555  SelectionDAG &DAG) {
2556  SDLoc DL(HiPart);
2557  EVT PtrVT = HiPart.getValueType();
2558  SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2559 
2560  SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2561  SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2562 
2563  // With PIC, the first instruction is actually "GR+hi(&G)".
2564  if (isPIC)
2565  Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2566  DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2567 
2568  // Generate non-pic code that has direct accesses to the constant pool.
2569  // The address of the global is just (hi(&g)+lo(&g)).
2570  return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2571 }
2572 
2574  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2575  FuncInfo->setUsesTOCBasePtr();
2576 }
2577 
2578 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2580 }
2581 
2582 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2583  SDValue GA) {
2584  EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2585  SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2586  DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2587 
2588  SDValue Ops[] = { GA, Reg };
2589  return DAG.getMemIntrinsicNode(
2590  PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2593 }
2594 
2595 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2596  SelectionDAG &DAG) const {
2597  EVT PtrVT = Op.getValueType();
2598  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2599  const Constant *C = CP->getConstVal();
2600 
2601  // 64-bit SVR4 ABI code is always position-independent.
2602  // The actual address of the GlobalValue is stored in the TOC.
2603  if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2604  setUsesTOCBasePtr(DAG);
2605  SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2606  return getTOCEntry(DAG, SDLoc(CP), true, GA);
2607  }
2608 
2609  unsigned MOHiFlag, MOLoFlag;
2610  bool IsPIC = isPositionIndependent();
2611  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2612 
2613  if (IsPIC && Subtarget.isSVR4ABI()) {
2614  SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2616  return getTOCEntry(DAG, SDLoc(CP), false, GA);
2617  }
2618 
2619  SDValue CPIHi =
2620  DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2621  SDValue CPILo =
2622  DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2623  return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2624 }
2625 
2626 // For 64-bit PowerPC, prefer the more compact relative encodings.
2627 // This trades 32 bits per jump table entry for one or two instructions
2628 // on the jump site.
2630  if (isJumpTableRelative())
2632 
2634 }
2635 
2637  if (Subtarget.isPPC64())
2638  return true;
2640 }
2641 
2643  SelectionDAG &DAG) const {
2644  if (!Subtarget.isPPC64())
2645  return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2646 
2647  switch (getTargetMachine().getCodeModel()) {
2648  case CodeModel::Small:
2649  case CodeModel::Medium:
2650  return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2651  default:
2652  return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2653  getPointerTy(DAG.getDataLayout()));
2654  }
2655 }
2656 
2657 const MCExpr *
2659  unsigned JTI,
2660  MCContext &Ctx) const {
2661  if (!Subtarget.isPPC64())
2662  return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2663 
2664  switch (getTargetMachine().getCodeModel()) {
2665  case CodeModel::Small:
2666  case CodeModel::Medium:
2667  return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2668  default:
2669  return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2670  }
2671 }
2672 
2673 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2674  EVT PtrVT = Op.getValueType();
2675  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2676 
2677  // 64-bit SVR4 ABI code is always position-independent.
2678  // The actual address of the GlobalValue is stored in the TOC.
2679  if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2680  setUsesTOCBasePtr(DAG);
2681  SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2682  return getTOCEntry(DAG, SDLoc(JT), true, GA);
2683  }
2684 
2685  unsigned MOHiFlag, MOLoFlag;
2686  bool IsPIC = isPositionIndependent();
2687  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2688 
2689  if (IsPIC && Subtarget.isSVR4ABI()) {
2690  SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2692  return getTOCEntry(DAG, SDLoc(GA), false, GA);
2693  }
2694 
2695  SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2696  SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2697  return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2698 }
2699 
2700 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2701  SelectionDAG &DAG) const {
2702  EVT PtrVT = Op.getValueType();
2703  BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2704  const BlockAddress *BA = BASDN->getBlockAddress();
2705 
2706  // 64-bit SVR4 ABI code is always position-independent.
2707  // The actual BlockAddress is stored in the TOC.
2708  if (Subtarget.isSVR4ABI() &&
2709  (Subtarget.isPPC64() || isPositionIndependent())) {
2710  if (Subtarget.isPPC64())
2711  setUsesTOCBasePtr(DAG);
2712  SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2713  return getTOCEntry(DAG, SDLoc(BASDN), Subtarget.isPPC64(), GA);
2714  }
2715 
2716  unsigned MOHiFlag, MOLoFlag;
2717  bool IsPIC = isPositionIndependent();
2718  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2719  SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2720  SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2721  return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2722 }
2723 
2724 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2725  SelectionDAG &DAG) const {
2726  // FIXME: TLS addresses currently use medium model code sequences,
2727  // which is the most useful form. Eventually support for small and
2728  // large models could be added if users need it, at the cost of
2729  // additional complexity.
2730  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2731  if (DAG.getTarget().useEmulatedTLS())
2732  return LowerToTLSEmulatedModel(GA, DAG);
2733 
2734  SDLoc dl(GA);
2735  const GlobalValue *GV = GA->getGlobal();
2736  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2737  bool is64bit = Subtarget.isPPC64();
2738  const Module *M = DAG.getMachineFunction().getFunction().getParent();
2739  PICLevel::Level picLevel = M->getPICLevel();
2740 
2742 
2743  if (Model == TLSModel::LocalExec) {
2744  SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2746  SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2748  SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2749  : DAG.getRegister(PPC::R2, MVT::i32);
2750 
2751  SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2752  return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2753  }
2754 
2755  if (Model == TLSModel::InitialExec) {
2756  SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2757  SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2758  PPCII::MO_TLS);
2759  SDValue GOTPtr;
2760  if (is64bit) {
2761  setUsesTOCBasePtr(DAG);
2762  SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2763  GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2764  PtrVT, GOTReg, TGA);
2765  } else
2766  GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2767  SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2768  PtrVT, TGA, GOTPtr);
2769  return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2770  }
2771 
2772  if (Model == TLSModel::GeneralDynamic) {
2773  SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2774  SDValue GOTPtr;
2775  if (is64bit) {
2776  setUsesTOCBasePtr(DAG);
2777  SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2778  GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2779  GOTReg, TGA);
2780  } else {
2781  if (picLevel == PICLevel::SmallPIC)
2782  GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2783  else
2784  GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2785  }
2786  return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2787  GOTPtr, TGA, TGA);
2788  }
2789 
2790  if (Model == TLSModel::LocalDynamic) {
2791  SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2792  SDValue GOTPtr;
2793  if (is64bit) {
2794  setUsesTOCBasePtr(DAG);
2795  SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2796  GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2797  GOTReg, TGA);
2798  } else {
2799  if (picLevel == PICLevel::SmallPIC)
2800  GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2801  else
2802  GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2803  }
2804  SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2805  PtrVT, GOTPtr, TGA, TGA);
2806  SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2807  PtrVT, TLSAddr, TGA);
2808  return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2809  }
2810 
2811  llvm_unreachable("Unknown TLS model!");
2812 }
2813 
2814 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2815  SelectionDAG &DAG) const {
2816  EVT PtrVT = Op.getValueType();
2817  GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2818  SDLoc DL(GSDN);
2819  const GlobalValue *GV = GSDN->getGlobal();
2820 
2821  // 64-bit SVR4 ABI code is always position-independent.
2822  // The actual address of the GlobalValue is stored in the TOC.
2823  if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2824  setUsesTOCBasePtr(DAG);
2825  SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2826  return getTOCEntry(DAG, DL, true, GA);
2827  }
2828 
2829  unsigned MOHiFlag, MOLoFlag;
2830  bool IsPIC = isPositionIndependent();
2831  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2832 
2833  if (IsPIC && Subtarget.isSVR4ABI()) {
2834  SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2835  GSDN->getOffset(),
2837  return getTOCEntry(DAG, DL, false, GA);
2838  }
2839 
2840  SDValue GAHi =
2841  DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2842  SDValue GALo =
2843  DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2844 
2845  SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2846 
2847  // If the global reference is actually to a non-lazy-pointer, we have to do an
2848  // extra load to get the address of the global.
2849  if (MOHiFlag & PPCII::MO_NLP_FLAG)
2850  Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2851  return Ptr;
2852 }
2853 
2854 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2855  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2856  SDLoc dl(Op);
2857 
2858  if (Op.getValueType() == MVT::v2i64) {
2859  // When the operands themselves are v2i64 values, we need to do something
2860  // special because VSX has no underlying comparison operations for these.
2861  if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2862  // Equality can be handled by casting to the legal type for Altivec
2863  // comparisons, everything else needs to be expanded.
2864  if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2865  return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2866  DAG.getSetCC(dl, MVT::v4i32,
2867  DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2868  DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2869  CC));
2870  }
2871 
2872  return SDValue();
2873  }
2874 
2875  // We handle most of these in the usual way.
2876  return Op;
2877  }
2878 
2879  // If we're comparing for equality to zero, expose the fact that this is
2880  // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2881  // fold the new nodes.
2882  if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2883  return V;
2884 
2885  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2886  // Leave comparisons against 0 and -1 alone for now, since they're usually
2887  // optimized. FIXME: revisit this when we can custom lower all setcc
2888  // optimizations.
2889  if (C->isAllOnesValue() || C->isNullValue())
2890  return SDValue();
2891  }
2892 
2893  // If we have an integer seteq/setne, turn it into a compare against zero
2894  // by xor'ing the rhs with the lhs, which is faster than setting a
2895  // condition register, reading it back out, and masking the correct bit. The
2896  // normal approach here uses sub to do this instead of xor. Using xor exposes
2897  // the result to other bit-twiddling opportunities.
2898  EVT LHSVT = Op.getOperand(0).getValueType();
2899  if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2900  EVT VT = Op.getValueType();
2901  SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2902  Op.getOperand(1));
2903  return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2904  }
2905  return SDValue();
2906 }
2907 
2908 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2909  SDNode *Node = Op.getNode();
2910  EVT VT = Node->getValueType(0);
2911  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2912  SDValue InChain = Node->getOperand(0);
2913  SDValue VAListPtr = Node->getOperand(1);
2914  const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2915  SDLoc dl(Node);
2916 
2917  assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2918 
2919  // gpr_index
2920  SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2921  VAListPtr, MachinePointerInfo(SV), MVT::i8);
2922  InChain = GprIndex.getValue(1);
2923 
2924  if (VT == MVT::i64) {
2925  // Check if GprIndex is even
2926  SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2927  DAG.getConstant(1, dl, MVT::i32));
2928  SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2929  DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2930  SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2931  DAG.getConstant(1, dl, MVT::i32));
2932  // Align GprIndex to be even if it isn't
2933  GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2934  GprIndex);
2935  }
2936 
2937  // fpr index is 1 byte after gpr
2938  SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2939  DAG.getConstant(1, dl, MVT::i32));
2940 
2941  // fpr
2942  SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2943  FprPtr, MachinePointerInfo(SV), MVT::i8);
2944  InChain = FprIndex.getValue(1);
2945 
2946  SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2947  DAG.getConstant(8, dl, MVT::i32));
2948 
2949  SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2950  DAG.getConstant(4, dl, MVT::i32));
2951 
2952  // areas
2953  SDValue OverflowArea =
2954  DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2955  InChain = OverflowArea.getValue(1);
2956 
2957  SDValue RegSaveArea =
2958  DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2959  InChain = RegSaveArea.getValue(1);
2960 
2961  // select overflow_area if index > 8
2962  SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2963  DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2964 
2965  // adjustment constant gpr_index * 4/8
2966  SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2967  VT.isInteger() ? GprIndex : FprIndex,
2968  DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2969  MVT::i32));
2970 
2971  // OurReg = RegSaveArea + RegConstant
2972  SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2973  RegConstant);
2974 
2975  // Floating types are 32 bytes into RegSaveArea
2976  if (VT.isFloatingPoint())
2977  OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2978  DAG.getConstant(32, dl, MVT::i32));
2979 
2980  // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2981  SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2982  VT.isInteger() ? GprIndex : FprIndex,
2983  DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2984  MVT::i32));
2985 
2986  InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2987  VT.isInteger() ? VAListPtr : FprPtr,
2989 
2990  // determine if we should load from reg_save_area or overflow_area
2991  SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2992 
2993  // increase overflow_area by 4/8 if gpr/fpr > 8
2994  SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2995  DAG.getConstant(VT.isInteger() ? 4 : 8,
2996  dl, MVT::i32));
2997 
2998  OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2999  OverflowAreaPlusN);
3000 
3001  InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3003 
3004  return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3005 }
3006 
3007 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3008  assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3009 
3010  // We have to copy the entire va_list struct:
3011  // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3012  return DAG.getMemcpy(Op.getOperand(0), Op,
3013  Op.getOperand(1), Op.getOperand(2),
3014  DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
3016 }
3017 
3018 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3019  SelectionDAG &DAG) const {
3020  return Op.getOperand(0);
3021 }
3022 
3023 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3024  SelectionDAG &DAG) const {
3025  SDValue Chain = Op.getOperand(0);
3026  SDValue Trmp = Op.getOperand(1); // trampoline
3027  SDValue FPtr = Op.getOperand(2); // nested function
3028  SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3029  SDLoc dl(Op);
3030 
3031  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3032  bool isPPC64 = (PtrVT == MVT::i64);
3033  Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3034 
3037 
3038  Entry.Ty = IntPtrTy;
3039  Entry.Node = Trmp; Args.push_back(Entry);
3040 
3041  // TrampSize == (isPPC64 ? 48 : 40);
3042  Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3043  isPPC64 ? MVT::i64 : MVT::i32);
3044  Args.push_back(Entry);
3045 
3046  Entry.Node = FPtr; Args.push_back(Entry);
3047  Entry.Node = Nest; Args.push_back(Entry);
3048 
3049  // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3051  CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3053  DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3054 
3055  std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3056  return CallResult.second;
3057 }
3058 
3059 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3060  MachineFunction &MF = DAG.getMachineFunction();
3061  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3062  EVT PtrVT = getPointerTy(MF.getDataLayout());
3063 
3064  SDLoc dl(Op);
3065 
3066  if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
3067  // vastart just stores the address of the VarArgsFrameIndex slot into the
3068  // memory location argument.
3069  SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3070  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3071  return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3072  MachinePointerInfo(SV));
3073  }
3074 
3075  // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3076  // We suppose the given va_list is already allocated.
3077  //
3078  // typedef struct {
3079  // char gpr; /* index into the array of 8 GPRs
3080  // * stored in the register save area
3081  // * gpr=0 corresponds to r3,
3082  // * gpr=1 to r4, etc.
3083  // */
3084  // char fpr; /* index into the array of 8 FPRs
3085  // * stored in the register save area
3086  // * fpr=0 corresponds to f1,
3087  // * fpr=1 to f2, etc.
3088  // */
3089  // char *overflow_arg_area;
3090  // /* location on stack that holds
3091  // * the next overflow argument
3092  // */
3093  // char *reg_save_area;
3094  // /* where r3:r10 and f1:f8 (if saved)
3095  // * are stored
3096  // */
3097  // } va_list[1];
3098 
3099  SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3100  SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3101  SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3102  PtrVT);
3103  SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3104  PtrVT);
3105 
3106  uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3107  SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3108 
3109  uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3110  SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3111 
3112  uint64_t FPROffset = 1;
3113  SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3114 
3115  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3116 
3117  // Store first byte : number of int regs
3118  SDValue firstStore =
3119  DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3121  uint64_t nextOffset = FPROffset;
3122  SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3123  ConstFPROffset);
3124 
3125  // Store second byte : number of float regs
3126  SDValue secondStore =
3127  DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3128  MachinePointerInfo(SV, nextOffset), MVT::i8);
3129  nextOffset += StackOffset;
3130  nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3131 
3132  // Store second word : arguments given on stack
3133  SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3134  MachinePointerInfo(SV, nextOffset));
3135  nextOffset += FrameOffset;
3136  nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3137 
3138  // Store third word : arguments given in registers
3139  return DAG.getStore(thirdStore, dl, FR, nextPtr,
3140  MachinePointerInfo(SV, nextOffset));
3141 }
3142 
3143 #include "PPCGenCallingConv.inc"
3144 
3145 // Function whose sole purpose is to kill compiler warnings
3146 // stemming from unused functions included from PPCGenCallingConv.inc.
3147 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
3148  return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
3149 }
3150 
3151 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
3152  CCValAssign::LocInfo &LocInfo,
3153  ISD::ArgFlagsTy &ArgFlags,
3154  CCState &State) {
3155  return true;
3156 }
3157 
3158 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
3159  MVT &LocVT,
3160  CCValAssign::LocInfo &LocInfo,
3161  ISD::ArgFlagsTy &ArgFlags,
3162  CCState &State) {
3163  static const MCPhysReg ArgRegs[] = {
3164  PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3165  PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3166  };
3167  const unsigned NumArgRegs = array_lengthof(ArgRegs);
3168 
3169  unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3170 
3171  // Skip one register if the first unallocated register has an even register
3172  // number and there are still argument registers available which have not been
3173  // allocated yet. RegNum is actually an index into ArgRegs, which means we
3174  // need to skip a register if RegNum is odd.
3175  if (RegNum != NumArgRegs && RegNum % 2 == 1) {
3176  State.AllocateReg(ArgRegs[RegNum]);
3177  }
3178 
3179  // Always return false here, as this function only makes sure that the first
3180  // unallocated register has an odd register number and does not actually
3181  // allocate a register for the current argument.
3182  return false;
3183 }
3184 
3185 bool
3187  MVT &LocVT,
3188  CCValAssign::LocInfo &LocInfo,
3189  ISD::ArgFlagsTy &ArgFlags,
3190  CCState &State) {
3191  static const MCPhysReg ArgRegs[] = {
3192  PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3193  PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3194  };
3195  const unsigned NumArgRegs = array_lengthof(ArgRegs);
3196 
3197  unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3198  int RegsLeft = NumArgRegs - RegNum;
3199 
3200  // Skip if there is not enough registers left for long double type (4 gpr regs
3201  // in soft float mode) and put long double argument on the stack.
3202  if (RegNum != NumArgRegs && RegsLeft < 4) {
3203  for (int i = 0; i < RegsLeft; i++) {
3204  State.AllocateReg(ArgRegs[RegNum + i]);
3205  }
3206  }
3207 
3208  return false;
3209 }
3210 
3211 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
3212  MVT &LocVT,
3213  CCValAssign::LocInfo &LocInfo,
3214  ISD::ArgFlagsTy &ArgFlags,
3215  CCState &State) {
3216  static const MCPhysReg ArgRegs[] = {
3217  PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3218  PPC::F8
3219  };
3220 
3221  const unsigned NumArgRegs = array_lengthof(ArgRegs);
3222 
3223  unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3224 
3225  // If there is only one Floating-point register left we need to put both f64
3226  // values of a split ppc_fp128 value on the stack.
3227  if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
3228  State.AllocateReg(ArgRegs[RegNum]);
3229  }
3230 
3231  // Always return false here, as this function only makes sure that the two f64
3232  // values a ppc_fp128 value is split into are both passed in registers or both
3233  // passed on the stack and does not actually allocate a register for the
3234  // current argument.
3235  return false;
3236 }
3237 
3238 /// FPR - The set of FP registers that should be allocated for arguments,
3239 /// on Darwin.
3240 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5,
3241  PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10,
3242  PPC::F11, PPC::F12, PPC::F13};
3243 
3244 /// QFPR - The set of QPX registers that should be allocated for arguments.
3245 static const MCPhysReg QFPR[] = {
3246  PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7,
3247  PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3248 
3249 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3250 /// the stack.
3251 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3252  unsigned PtrByteSize) {
3253  unsigned ArgSize = ArgVT.getStoreSize();
3254  if (Flags.isByVal())
3255  ArgSize = Flags.getByValSize();
3256 
3257  // Round up to multiples of the pointer size, except for array members,
3258  // which are always packed.
3259  if (!Flags.isInConsecutiveRegs())
3260  ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3261 
3262  return ArgSize;
3263 }
3264 
3265 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3266 /// on the stack.
3267 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3268  ISD::ArgFlagsTy Flags,
3269  unsigned PtrByteSize) {
3270  unsigned Align = PtrByteSize;
3271 
3272  // Altivec parameters are padded to a 16 byte boundary.
3273  if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3274  ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3275  ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3276  ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3277  Align = 16;
3278  // QPX vector types stored in double-precision are padded to a 32 byte
3279  // boundary.
3280  else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3281  Align = 32;
3282 
3283  // ByVal parameters are aligned as requested.
3284  if (Flags.isByVal()) {
3285  unsigned BVAlign = Flags.getByValAlign();
3286  if (BVAlign > PtrByteSize) {
3287  if (BVAlign % PtrByteSize != 0)
3289  "ByVal alignment is not a multiple of the pointer size");
3290 
3291  Align = BVAlign;
3292  }
3293  }
3294 
3295  // Array members are always packed to their original alignment.
3296  if (Flags.isInConsecutiveRegs()) {
3297  // If the array member was split into multiple registers, the first
3298  // needs to be aligned to the size of the full type. (Except for
3299  // ppcf128, which is only aligned as its f64 components.)
3300  if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3301  Align = OrigVT.getStoreSize();
3302  else
3303  Align = ArgVT.getStoreSize();
3304  }
3305 
3306  return Align;
3307 }
3308 
3309 /// CalculateStackSlotUsed - Return whether this argument will use its
3310 /// stack slot (instead of being passed in registers). ArgOffset,
3311 /// AvailableFPRs, and AvailableVRs must hold the current argument
3312 /// position, and will be updated to account for this argument.
3313 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3314  ISD::ArgFlagsTy Flags,
3315  unsigned PtrByteSize,
3316  unsigned LinkageSize,
3317  unsigned ParamAreaSize,
3318  unsigned &ArgOffset,
3319  unsigned &AvailableFPRs,
3320  unsigned &AvailableVRs, bool HasQPX) {
3321  bool UseMemory = false;
3322 
3323  // Respect alignment of argument on the stack.
3324  unsigned Align =
3325  CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3326  ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3327  // If there's no space left in the argument save area, we must
3328  // use memory (this check also catches zero-sized arguments).
3329  if (ArgOffset >= LinkageSize + ParamAreaSize)
3330  UseMemory = true;
3331 
3332  // Allocate argument on the stack.
3333  ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3334  if (Flags.isInConsecutiveRegsLast())
3335  ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3336  // If we overran the argument save area, we must use memory
3337  // (this check catches arguments passed partially in memory)
3338  if (ArgOffset > LinkageSize + ParamAreaSize)
3339  UseMemory = true;
3340 
3341  // However, if the argument is actually passed in an FPR or a VR,
3342  // we don't use memory after all.
3343  if (!Flags.isByVal()) {
3344  if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3345  // QPX registers overlap with the scalar FP registers.
3346  (HasQPX && (ArgVT == MVT::v4f32 ||
3347  ArgVT == MVT::v4f64 ||
3348  ArgVT == MVT::v4i1)))
3349  if (AvailableFPRs > 0) {
3350  --AvailableFPRs;
3351  return false;
3352  }
3353  if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3354  ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3355  ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3356  ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3357  if (AvailableVRs > 0) {
3358  --AvailableVRs;
3359  return false;
3360  }
3361  }
3362 
3363  return UseMemory;
3364 }
3365 
3366 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3367 /// ensure minimum alignment required for target.
3369  unsigned NumBytes) {
3370  unsigned TargetAlign = Lowering->getStackAlignment();
3371  unsigned AlignMask = TargetAlign - 1;
3372  NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3373  return NumBytes;
3374 }
3375 
3376 SDValue PPCTargetLowering::LowerFormalArguments(
3377  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3378  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3379  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3380  if (Subtarget.isSVR4ABI()) {
3381  if (Subtarget.isPPC64())
3382  return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
3383  dl, DAG, InVals);
3384  else
3385  return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
3386  dl, DAG, InVals);
3387  } else {
3388  return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
3389  dl, DAG, InVals);
3390  }
3391 }
3392 
3393 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3394  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3395  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3396  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3397 
3398  // 32-bit SVR4 ABI Stack Frame Layout:
3399  // +-----------------------------------+
3400  // +--> | Back chain |
3401  // | +-----------------------------------+
3402  // | | Floating-point register save area |
3403  // | +-----------------------------------+
3404  // | | General register save area |
3405  // | +-----------------------------------+
3406  // | | CR save word |
3407  // | +-----------------------------------+
3408  // | | VRSAVE save word |
3409  // | +-----------------------------------+
3410  // | | Alignment padding |
3411  // | +-----------------------------------+
3412  // | | Vector register save area |
3413  // | +-----------------------------------+
3414  // | | Local variable space |
3415  // | +-----------------------------------+
3416  // | | Parameter list area |
3417  // | +-----------------------------------+
3418  // | | LR save word |
3419  // | +-----------------------------------+
3420  // SP--> +--- | Back chain |
3421  // +-----------------------------------+
3422  //
3423  // Specifications:
3424  // System V Application Binary Interface PowerPC Processor Supplement
3425  // AltiVec Technology Programming Interface Manual
3426 
3427  MachineFunction &MF = DAG.getMachineFunction();
3428  MachineFrameInfo &MFI = MF.getFrameInfo();
3429  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3430 
3431  EVT PtrVT = getPointerTy(MF.getDataLayout());
3432  // Potential tail calls could cause overwriting of argument stack slots.
3433  bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3434  (CallConv == CallingConv::Fast));
3435  unsigned PtrByteSize = 4;
3436 
3437  // Assign locations to all of the incoming arguments.
3439  PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3440  *DAG.getContext());
3441 
3442  // Reserve space for the linkage area on the stack.
3443  unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3444  CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3445  if (useSoftFloat() || hasSPE())
3446  CCInfo.PreAnalyzeFormalArguments(Ins);
3447 
3448  CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3449  CCInfo.clearWasPPCF128();
3450 
3451  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3452  CCValAssign &VA = ArgLocs[i];
3453 
3454  // Arguments stored in registers.
3455  if (VA.isRegLoc()) {
3456  const TargetRegisterClass *RC;
3457  EVT ValVT = VA.getValVT();
3458 
3459  switch (ValVT.getSimpleVT().SimpleTy) {
3460  default:
3461  llvm_unreachable("ValVT not supported by formal arguments Lowering");
3462  case MVT::i1:
3463  case MVT::i32:
3464  RC = &PPC::GPRCRegClass;
3465  break;
3466  case MVT::f32:
3467  if (Subtarget.hasP8Vector())
3468  RC = &PPC::VSSRCRegClass;
3469  else if (Subtarget.hasSPE())
3470  RC = &PPC::SPE4RCRegClass;
3471  else
3472  RC = &PPC::F4RCRegClass;
3473  break;
3474  case MVT::f64:
3475  if (Subtarget.hasVSX())
3476  RC = &PPC::VSFRCRegClass;
3477  else if (Subtarget.hasSPE())
3478  RC = &PPC::SPERCRegClass;
3479  else
3480  RC = &PPC::F8RCRegClass;
3481  break;
3482  case MVT::v16i8:
3483  case MVT::v8i16:
3484  case MVT::v4i32:
3485  RC = &PPC::VRRCRegClass;
3486  break;
3487  case MVT::v4f32:
3488  RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3489  break;
3490  case MVT::v2f64:
3491  case MVT::v2i64:
3492  RC = &PPC::VRRCRegClass;
3493  break;
3494  case MVT::v4f64:
3495  RC = &PPC::QFRCRegClass;
3496  break;
3497  case MVT::v4i1:
3498  RC = &PPC::QBRCRegClass;
3499  break;
3500  }
3501 
3502  // Transform the arguments stored in physical registers into virtual ones.
3503  unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3504  SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3505  ValVT == MVT::i1 ? MVT::i32 : ValVT);
3506 
3507  if (ValVT == MVT::i1)
3508  ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3509 
3510  InVals.push_back(ArgValue);
3511  } else {
3512  // Argument stored in memory.
3513  assert(VA.isMemLoc());
3514 
3515  // Get the extended size of the argument type in stack
3516  unsigned ArgSize = VA.getLocVT().getStoreSize();
3517  // Get the actual size of the argument type
3518  unsigned ObjSize = VA.getValVT().getStoreSize();
3519  unsigned ArgOffset = VA.getLocMemOffset();
3520  // Stack objects in PPC32 are right justified.
3521  ArgOffset += ArgSize - ObjSize;
3522  int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3523 
3524  // Create load nodes to retrieve arguments from the stack.
3525  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3526  InVals.push_back(
3527  DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3528  }
3529  }
3530 
3531  // Assign locations to all of the incoming aggregate by value arguments.
3532  // Aggregates passed by value are stored in the local variable space of the
3533  // caller's stack frame, right above the parameter list area.
3534  SmallVector<CCValAssign, 16> ByValArgLocs;
3535  CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3536  ByValArgLocs, *DAG.getContext());
3537 
3538  // Reserve stack space for the allocations in CCInfo.
3539  CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3540 
3541  CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3542 
3543  // Area that is at least reserved in the caller of this function.
3544  unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3545  MinReservedArea = std::max(MinReservedArea, LinkageSize);
3546 
3547  // Set the size that is at least reserved in caller of this function. Tail
3548  // call optimized function's reserved stack space needs to be aligned so that
3549  // taking the difference between two stack areas will result in an aligned
3550  // stack.
3551  MinReservedArea =
3552  EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3553  FuncInfo->setMinReservedArea(MinReservedArea);
3554 
3555  SmallVector<SDValue, 8> MemOps;
3556 
3557  // If the function takes variable number of arguments, make a frame index for
3558  // the start of the first vararg value... for expansion of llvm.va_start.
3559  if (isVarArg) {
3560  static const MCPhysReg GPArgRegs[] = {
3561  PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3562  PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3563  };
3564  const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3565 
3566  static const MCPhysReg FPArgRegs[] = {
3567  PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3568  PPC::F8
3569  };
3570  unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3571 
3572  if (useSoftFloat() || hasSPE())
3573  NumFPArgRegs = 0;
3574 
3575  FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3576  FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3577 
3578  // Make room for NumGPArgRegs and NumFPArgRegs.
3579  int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3580  NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3581 
3582  FuncInfo->setVarArgsStackOffset(
3583  MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3584  CCInfo.getNextStackOffset(), true));
3585 
3586  FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3587  SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3588 
3589  // The fixed integer arguments of a variadic function are stored to the
3590  // VarArgsFrameIndex on the stack so that they may be loaded by
3591  // dereferencing the result of va_next.
3592  for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3593  // Get an existing live-in vreg, or add a new one.
3594  unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3595  if (!VReg)
3596  VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3597 
3598  SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3599  SDValue Store =
3600  DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3601  MemOps.push_back(Store);
3602  // Increment the address by four for the next argument to store
3603  SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3604  FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3605  }
3606 
3607  // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3608  // is set.
3609  // The double arguments are stored to the VarArgsFrameIndex
3610  // on the stack.
3611  for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3612  // Get an existing live-in vreg, or add a new one.
3613  unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3614  if (!VReg)
3615  VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3616 
3617  SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3618  SDValue Store =
3619  DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3620  MemOps.push_back(Store);
3621  // Increment the address by eight for the next argument to store
3622  SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3623  PtrVT);
3624  FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3625  }
3626  }
3627 
3628  if (!MemOps.empty())
3629  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3630 
3631  return Chain;
3632 }
3633 
3634 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3635 // value to MVT::i64 and then truncate to the correct register size.
3636 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3637  EVT ObjectVT, SelectionDAG &DAG,
3638  SDValue ArgVal,
3639  const SDLoc &dl) const {
3640  if (Flags.isSExt())
3641  ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3642  DAG.getValueType(ObjectVT));
3643  else if (Flags.isZExt())
3644  ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3645  DAG.getValueType(ObjectVT));
3646 
3647  return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3648 }
3649 
3650 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3651  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3652  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3653  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3654  // TODO: add description of PPC stack frame format, or at least some docs.
3655  //
3656  bool isELFv2ABI = Subtarget.isELFv2ABI();
3657  bool isLittleEndian = Subtarget.isLittleEndian();
3658  MachineFunction &MF = DAG.getMachineFunction();
3659  MachineFrameInfo &MFI = MF.getFrameInfo();
3660  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3661 
3662  assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3663  "fastcc not supported on varargs functions");
3664 
3665  EVT PtrVT = getPointerTy(MF.getDataLayout());
3666  // Potential tail calls could cause overwriting of argument stack slots.
3667  bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3668  (CallConv == CallingConv::Fast));
3669  unsigned PtrByteSize = 8;
3670  unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3671 
3672  static const MCPhysReg GPR[] = {
3673  PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3674  PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3675  };
3676  static const MCPhysReg VR[] = {
3677  PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3678  PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3679  };
3680 
3681  const unsigned Num_GPR_Regs = array_lengthof(GPR);
3682  const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3683  const unsigned Num_VR_Regs = array_lengthof(VR);
3684  const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3685 
3686  // Do a first pass over the arguments to determine whether the ABI
3687  // guarantees that our caller has allocated the parameter save area
3688  // on its stack frame. In the ELFv1 ABI, this is always the case;
3689  // in the ELFv2 ABI, it is true if this is a vararg function or if
3690  // any parameter is located in a stack slot.
3691 
3692  bool HasParameterArea = !isELFv2ABI || isVarArg;
3693  unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3694  unsigned NumBytes = LinkageSize;
3695  unsigned AvailableFPRs = Num_FPR_Regs;
3696  unsigned AvailableVRs = Num_VR_Regs;
3697  for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3698  if (Ins[i].Flags.isNest())
3699  continue;
3700 
3701  if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3702  PtrByteSize, LinkageSize, ParamAreaSize,
3703  NumBytes, AvailableFPRs, AvailableVRs,
3704  Subtarget.hasQPX()))
3705  HasParameterArea = true;
3706  }
3707 
3708  // Add DAG nodes to load the arguments or copy them out of registers. On
3709  // entry to a function on PPC, the arguments start after the linkage area,
3710  // although the first ones are often in registers.
3711 
3712  unsigned ArgOffset = LinkageSize;
3713  unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3714  unsigned &QFPR_idx = FPR_idx;
3715  SmallVector<SDValue, 8> MemOps;
3717  unsigned CurArgIdx = 0;
3718  for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3719  SDValue ArgVal;
3720  bool needsLoad = false;
3721  EVT ObjectVT = Ins[ArgNo].VT;
3722  EVT OrigVT = Ins[ArgNo].ArgVT;
3723  unsigned ObjSize = ObjectVT.getStoreSize();
3724  unsigned ArgSize = ObjSize;
3725  ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3726  if (Ins[ArgNo].isOrigArg()) {
3727  std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3728  CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3729  }
3730  // We re-align the argument offset for each argument, except when using the
3731  // fast calling convention, when we need to make sure we do that only when
3732  // we'll actually use a stack slot.
3733  unsigned CurArgOffset, Align;
3734  auto ComputeArgOffset = [&]() {
3735  /* Respect alignment of argument on the stack. */
3736  Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3737  ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3738  CurArgOffset = ArgOffset;
3739  };
3740 
3741  if (CallConv != CallingConv::Fast) {
3742  ComputeArgOffset();
3743 
3744  /* Compute GPR index associated with argument offset. */
3745  GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3746  GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3747  }
3748 
3749  // FIXME the codegen can be much improved in some cases.
3750  // We do not have to keep everything in memory.
3751  if (Flags.isByVal()) {
3752  assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3753 
3754  if (CallConv == CallingConv::Fast)
3755  ComputeArgOffset();
3756 
3757  // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3758  ObjSize = Flags.getByValSize();
3759  ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3760  // Empty aggregate parameters do not take up registers. Examples:
3761  // struct { } a;
3762  // union { } b;
3763  // int c[0];
3764  // etc. However, we have to provide a place-holder in InVals, so
3765  // pretend we have an 8-byte item at the current address for that
3766  // purpose.
3767  if (!ObjSize) {
3768  int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3769  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3770  InVals.push_back(FIN);
3771  continue;
3772  }
3773 
3774  // Create a stack object covering all stack doublewords occupied
3775  // by the argument. If the argument is (fully or partially) on
3776  // the stack, or if the argument is fully in registers but the
3777  // caller has allocated the parameter save anyway, we can refer
3778  // directly to the caller's stack frame. Otherwise, create a
3779  // local copy in our own frame.
3780  int FI;
3781  if (HasParameterArea ||
3782  ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3783  FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3784  else
3785  FI = MFI.CreateStackObject(ArgSize, Align, false);
3786  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3787 
3788  // Handle aggregates smaller than 8 bytes.
3789  if (ObjSize < PtrByteSize) {
3790  // The value of the object is its address, which differs from the
3791  // address of the enclosing doubleword on big-endian systems.
3792  SDValue Arg = FIN;
3793  if (!isLittleEndian) {
3794  SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3795  Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3796  }
3797  InVals.push_back(Arg);
3798 
3799  if (GPR_idx != Num_GPR_Regs) {
3800  unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3801  FuncInfo->addLiveInAttr(VReg, Flags);
3802  SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3803  SDValue Store;
3804 
3805  if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3806  EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3807  (ObjSize == 2 ? MVT::i16 : MVT::i32));
3808  Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3809  MachinePointerInfo(&*FuncArg), ObjType);
3810  } else {
3811  // For sizes that don't fit a truncating store (3, 5, 6, 7),
3812  // store the whole register as-is to the parameter save area
3813  // slot.
3814  Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3815  MachinePointerInfo(&*FuncArg));
3816  }
3817 
3818  MemOps.push_back(Store);
3819  }
3820  // Whether we copied from a register or not, advance the offset
3821  // into the parameter save area by a full doubleword.
3822  ArgOffset += PtrByteSize;
3823  continue;
3824  }
3825 
3826  // The value of the object is its address, which is the address of
3827  // its first stack doubleword.
3828  InVals.push_back(FIN);
3829 
3830  // Store whatever pieces of the object are in registers to memory.
3831  for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3832  if (GPR_idx == Num_GPR_Regs)
3833  break;
3834 
3835  unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3836  FuncInfo->addLiveInAttr(VReg, Flags);
3837  SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3838  SDValue Addr = FIN;
3839  if (j) {
3840  SDValue Off = DAG.getConstant(j, dl, PtrVT);
3841  Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3842  }
3843  SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3844  MachinePointerInfo(&*FuncArg, j));
3845  MemOps.push_back(Store);
3846  ++GPR_idx;
3847  }
3848  ArgOffset += ArgSize;
3849  continue;
3850  }
3851 
3852  switch (ObjectVT.getSimpleVT().SimpleTy) {
3853  default: llvm_unreachable("Unhandled argument type!");
3854  case MVT::i1:
3855  case MVT::i32:
3856  case MVT::i64:
3857  if (Flags.isNest()) {
3858  // The 'nest' parameter, if any, is passed in R11.
3859  unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3860  ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3861 
3862  if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3863  ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3864 
3865  break;
3866  }
3867 
3868  // These can be scalar arguments or elements of an integer array type
3869  // passed directly. Clang may use those instead of "byval" aggregate
3870  // types to avoid forcing arguments to memory unnecessarily.
3871  if (GPR_idx != Num_GPR_Regs) {
3872  unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3873  FuncInfo->addLiveInAttr(VReg, Flags);
3874  ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3875 
3876  if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3877  // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3878  // value to MVT::i64 and then truncate to the correct register size.
3879  ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3880  } else {
3881  if (CallConv == CallingConv::Fast)
3882  ComputeArgOffset();
3883 
3884  needsLoad = true;
3885  ArgSize = PtrByteSize;
3886  }
3887  if (CallConv != CallingConv::Fast || needsLoad)
3888  ArgOffset += 8;
3889  break;
3890 
3891  case MVT::f32:
3892  case MVT::f64:
3893  // These can be scalar arguments or elements of a float array type
3894  // passed directly. The latter are used to implement ELFv2 homogenous
3895  // float aggregates.
3896  if (FPR_idx != Num_FPR_Regs) {
3897  unsigned VReg;
3898 
3899  if (ObjectVT == MVT::f32)
3900  VReg = MF.addLiveIn(FPR[FPR_idx],
3901  Subtarget.hasP8Vector()
3902  ? &PPC::VSSRCRegClass
3903  : &PPC::F4RCRegClass);
3904  else
3905  VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3906  ? &PPC::VSFRCRegClass
3907  : &PPC::F8RCRegClass);
3908 
3909  ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3910  ++FPR_idx;
3911  } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3912  // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3913  // once we support fp <-> gpr moves.
3914 
3915  // This can only ever happen in the presence of f32 array types,
3916  // since otherwise we never run out of FPRs before running out
3917  // of GPRs.
3918  unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3919  FuncInfo->addLiveInAttr(VReg, Flags);
3920  ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3921 
3922  if (ObjectVT == MVT::f32) {
3923  if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3924  ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3925  DAG.getConstant(32, dl, MVT::i32));
3926  ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3927  }
3928 
3929  ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3930  } else {
3931  if (CallConv == CallingConv::Fast)
3932  ComputeArgOffset();
3933 
3934  needsLoad = true;
3935  }
3936 
3937  // When passing an array of floats, the array occupies consecutive
3938  // space in the argument area; only round up to the next doubleword
3939  // at the end of the array. Otherwise, each float takes 8 bytes.
3940  if (CallConv != CallingConv::Fast || needsLoad) {
3941  ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3942  ArgOffset += ArgSize;
3943  if (Flags.isInConsecutiveRegsLast())
3944  ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3945  }
3946  break;
3947  case MVT::v4f32:
3948  case MVT::v4i32:
3949  case MVT::v8i16:
3950  case MVT::v16i8:
3951  case MVT::v2f64:
3952  case MVT::v2i64:
3953  case MVT::v1i128:
3954  case MVT::f128:
3955  if (!Subtarget.hasQPX()) {
3956  // These can be scalar arguments or elements of a vector array type
3957  // passed directly. The latter are used to implement ELFv2 homogenous
3958  // vector aggregates.
3959  if (VR_idx != Num_VR_Regs) {
3960  unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3961  ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3962  ++VR_idx;
3963  } else {
3964  if (CallConv == CallingConv::Fast)
3965  ComputeArgOffset();
3966  needsLoad = true;
3967  }
3968  if (CallConv != CallingConv::Fast || needsLoad)
3969  ArgOffset += 16;
3970  break;
3971  } // not QPX
3972 
3973  assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3974  "Invalid QPX parameter type");
3975  /* fall through */
3976 
3977  case MVT::v4f64:
3978  case MVT::v4i1:
3979  // QPX vectors are treated like their scalar floating-point subregisters
3980  // (except that they're larger).
3981  unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3982  if (QFPR_idx != Num_QFPR_Regs) {
3983  const TargetRegisterClass *RC;
3984  switch (ObjectVT.getSimpleVT().SimpleTy) {
3985  case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3986  case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3987  default: RC = &PPC::QBRCRegClass; break;
3988  }
3989 
3990  unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3991  ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3992  ++QFPR_idx;
3993  } else {
3994  if (CallConv == CallingConv::Fast)
3995  ComputeArgOffset();
3996  needsLoad = true;
3997  }
3998  if (CallConv != CallingConv::Fast || needsLoad)
3999  ArgOffset += Sz;
4000  break;
4001  }
4002 
4003  // We need to load the argument to a virtual register if we determined
4004  // above that we ran out of physical registers of the appropriate type.
4005  if (needsLoad) {
4006  if (ObjSize < ArgSize && !isLittleEndian)
4007  CurArgOffset += ArgSize - ObjSize;
4008  int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4009  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4010  ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4011  }
4012 
4013  InVals.push_back(ArgVal);
4014  }
4015 
4016  // Area that is at least reserved in the caller of this function.
4017  unsigned MinReservedArea;
4018  if (HasParameterArea)
4019  MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4020  else
4021  MinReservedArea = LinkageSize;
4022 
4023  // Set the size that is at least reserved in caller of this function. Tail
4024  // call optimized functions' reserved stack space needs to be aligned so that
4025  // taking the difference between two stack areas will result in an aligned
4026  // stack.
4027  MinReservedArea =
4028  EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4029  FuncInfo->setMinReservedArea(MinReservedArea);
4030 
4031  // If the function takes variable number of arguments, make a frame index for
4032  // the start of the first vararg value... for expansion of llvm.va_start.
4033  if (isVarArg) {
4034  int Depth = ArgOffset;
4035 
4036  FuncInfo->setVarArgsFrameIndex(
4037  MFI.CreateFixedObject(PtrByteSize, Depth, true));
4038  SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4039 
4040  // If this function is vararg, store any remaining integer argument regs
4041  // to their spots on the stack so that they may be loaded by dereferencing
4042  // the result of va_next.
4043  for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4044  GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4045  unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4046  SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4047  SDValue Store =
4048  DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4049  MemOps.push_back(Store);
4050  // Increment the address by four for the next argument to store
4051  SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4052  FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4053  }
4054  }
4055 
4056  if (!MemOps.empty())
4057  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4058 
4059  return Chain;
4060 }
4061 
4062 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4063  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4064  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4065  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4066  // TODO: add description of PPC stack frame format, or at least some docs.
4067  //
4068  MachineFunction &MF = DAG.getMachineFunction();
4069  MachineFrameInfo &MFI = MF.getFrameInfo();
4070  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4071 
4072  EVT PtrVT = getPointerTy(MF.getDataLayout());
4073  bool isPPC64 = PtrVT == MVT::i64;
4074  // Potential tail calls could cause overwriting of argument stack slots.
4075  bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4076  (CallConv == CallingConv::Fast));
4077  unsigned PtrByteSize = isPPC64 ? 8 : 4;
4078  unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4079  unsigned ArgOffset = LinkageSize;
4080  // Area that is at least reserved in caller of this function.
4081  unsigned MinReservedArea = ArgOffset;
4082 
4083  static const MCPhysReg GPR_32[] = { // 32-bit registers.
4084  PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4085  PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4086  };
4087  static const MCPhysReg GPR_64[] = { // 64-bit registers.
4088  PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4089  PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4090  };
4091  static const MCPhysReg VR[] = {
4092  PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4093  PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4094  };
4095 
4096  const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4097  const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4098  const unsigned Num_VR_Regs = array_lengthof( VR);
4099 
4100  unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4101 
4102  const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4103 
4104  // In 32-bit non-varargs functions, the stack space for vectors is after the
4105  // stack space for non-vectors. We do not use this space unless we have
4106  // too many vectors to fit in registers, something that only occurs in
4107  // constructed examples:), but we have to walk the arglist to figure
4108  // that out...for the pathological case, compute VecArgOffset as the
4109  // start of the vector parameter area. Computing VecArgOffset is the
4110  // entire point of the following loop.
4111  unsigned VecArgOffset = ArgOffset;
4112  if (!isVarArg && !isPPC64) {
4113  for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4114  ++ArgNo) {
4115  EVT ObjectVT = Ins[ArgNo].VT;
4116  ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4117 
4118  if (Flags.isByVal()) {
4119  // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4120  unsigned ObjSize = Flags.getByValSize();
4121  unsigned ArgSize =
4122  ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4123  VecArgOffset += ArgSize;
4124  continue;
4125  }
4126 
4127  switch(ObjectVT.getSimpleVT().SimpleTy) {
4128  default: llvm_unreachable("Unhandled argument type!");
4129  case MVT::i1:
4130  case MVT::i32:
4131  case MVT::f32:
4132  VecArgOffset += 4;
4133  break;
4134  case MVT::i64: // PPC64
4135  case MVT::f64:
4136  // FIXME: We are guaranteed to be !isPPC64 at this point.
4137  // Does MVT::i64 apply?
4138  VecArgOffset += 8;
4139  break;
4140  case MVT::v4f32:
4141  case MVT::v4i32:
4142  case MVT::v8i16:
4143  case MVT::v16i8:
4144  // Nothing to do, we're only looking at Nonvector args here.
4145  break;
4146  }
4147  }
4148  }
4149  // We've found where the vector parameter area in memory is. Skip the
4150  // first 12 parameters; these don't use that memory.
4151  VecArgOffset = ((VecArgOffset+15)/16)*16;
4152  VecArgOffset += 12*16;
4153 
4154  // Add DAG nodes to load the arguments or copy them out of registers. On
4155  // entry to a function on PPC, the arguments start after the linkage area,
4156  // although the first ones are often in registers.
4157 
4158  SmallVector<SDValue, 8> MemOps;
4159  unsigned nAltivecParamsAtEnd = 0;
4161  unsigned CurArgIdx = 0;
4162  for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {