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