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