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