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