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