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