LLVM  13.0.0git
PPCISelLowering.cpp
Go to the documentation of this file.
1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the PPCISelLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PPCISelLowering.h"
15 #include "PPC.h"
16 #include "PPCCCState.h"
17 #include "PPCCallingConv.h"
18 #include "PPCFrameLowering.h"
19 #include "PPCInstrInfo.h"
20 #include "PPCMachineFunctionInfo.h"
21 #include "PPCPerfectShuffle.h"
22 #include "PPCRegisterInfo.h"
23 #include "PPCSubtarget.h"
24 #include "PPCTargetMachine.h"
25 #include "llvm/ADT/APFloat.h"
26 #include "llvm/ADT/APInt.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/None.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/StringSwitch.h"
58 #include "llvm/IR/CallingConv.h"
59 #include "llvm/IR/Constant.h"
60 #include "llvm/IR/Constants.h"
61 #include "llvm/IR/DataLayout.h"
62 #include "llvm/IR/DebugLoc.h"
63 #include "llvm/IR/DerivedTypes.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/GlobalValue.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/Intrinsics.h"
69 #include "llvm/IR/IntrinsicsPowerPC.h"
70 #include "llvm/IR/Module.h"
71 #include "llvm/IR/Type.h"
72 #include "llvm/IR/Use.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/MC/MCContext.h"
75 #include "llvm/MC/MCExpr.h"
76 #include "llvm/MC/MCRegisterInfo.h"
77 #include "llvm/MC/MCSectionXCOFF.h"
78 #include "llvm/MC/MCSymbolXCOFF.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/CodeGen.h"
84 #include "llvm/Support/Compiler.h"
85 #include "llvm/Support/Debug.h"
87 #include "llvm/Support/Format.h"
88 #include "llvm/Support/KnownBits.h"
94 #include <algorithm>
95 #include <cassert>
96 #include <cstdint>
97 #include <iterator>
98 #include <list>
99 #include <utility>
100 #include <vector>
101 
102 using namespace llvm;
103 
104 #define DEBUG_TYPE "ppc-lowering"
105 
106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
108 
109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
111 
112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
114 
115 static cl::opt<bool> DisableSCO("disable-ppc-sco",
116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
117 
118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
120 
121 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
122 cl::desc("use absolute jump tables on ppc"), cl::Hidden);
123 
124 // TODO - Remove this option if soft fp128 has been fully supported .
125 static cl::opt<bool>
126  EnableSoftFP128("enable-soft-fp128",
127  cl::desc("temp option to enable soft fp128"), cl::Hidden);
128 
129 STATISTIC(NumTailCalls, "Number of tail calls");
130 STATISTIC(NumSiblingCalls, "Number of sibling calls");
131 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM");
132 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
133 
134 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
135 
136 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
137 
138 // FIXME: Remove this once the bug has been fixed!
140 
142  const PPCSubtarget &STI)
143  : TargetLowering(TM), Subtarget(STI) {
144  // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
145  // arguments are at least 4/8 bytes aligned.
146  bool isPPC64 = Subtarget.isPPC64();
147  setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
148 
149  // Set up the register classes.
150  addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
151  if (!useSoftFloat()) {
152  if (hasSPE()) {
153  addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
154  // EFPU2 APU only supports f32
155  if (!Subtarget.hasEFPU2())
156  addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
157  } else {
158  addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
159  addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
160  }
161  }
162 
163  // Match BITREVERSE to customized fast code sequence in the td file.
166 
167  // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
169 
170  // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
171  for (MVT VT : MVT::integer_valuetypes()) {
174  }
175 
176  if (Subtarget.isISA3_0()) {
181  } else {
182  // No extending loads from f16 or HW conversions back and forth.
191  }
192 
194 
195  // PowerPC has pre-inc load and store's.
206  if (!Subtarget.hasSPE()) {
211  }
212 
213  // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
214  const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
215  for (MVT VT : ScalarIntVTs) {
220  }
221 
222  if (Subtarget.useCRBits()) {
224 
225  if (isPPC64 || Subtarget.hasFPCVT()) {
228  isPPC64 ? MVT::i64 : MVT::i32);
231  isPPC64 ? MVT::i64 : MVT::i32);
232 
235  isPPC64 ? MVT::i64 : MVT::i32);
238  isPPC64 ? MVT::i64 : MVT::i32);
239 
242  isPPC64 ? MVT::i64 : MVT::i32);
245  isPPC64 ? MVT::i64 : MVT::i32);
246 
249  isPPC64 ? MVT::i64 : MVT::i32);
252  isPPC64 ? MVT::i64 : MVT::i32);
253  } else {
258  }
259 
260  // PowerPC does not support direct load/store of condition registers.
263 
264  // FIXME: Remove this once the ANDI glue bug is fixed:
265  if (ANDIGlueBug)
267 
268  for (MVT VT : MVT::integer_valuetypes()) {
272  }
273 
274  addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
275  }
276 
277  // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
278  // PPC (the libcall is not available).
283 
284  // We do not currently implement these libm ops for PowerPC.
291 
292  // PowerPC has no SREM/UREM instructions unless we are on P9
293  // On P9 we may use a hardware instruction to compute the remainder.
294  // When the result of both the remainder and the division is required it is
295  // more efficient to compute the remainder from the result of the division
296  // rather than use the remainder instruction. The instructions are legalized
297  // directly because the DivRemPairsPass performs the transformation at the IR
298  // level.
299  if (Subtarget.isISA3_0()) {
304  } else {
309  }
310 
311  // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
320 
321  // Handle constrained floating-point operations of scalar.
322  // TODO: Handle SPE specific operation.
329 
335  if (Subtarget.hasVSX()) {
338  }
339 
340  if (Subtarget.hasFSQRT()) {
343  }
344 
345  if (Subtarget.hasFPRND()) {
350 
355  }
356 
357  // We don't support sin/cos/sqrt/fmod/pow
368  if (Subtarget.hasSPE()) {
371  } else {
374  }
375 
376  if (Subtarget.hasSPE())
378 
380 
381  // If we're enabling GP optimizations, use hardware square root
382  if (!Subtarget.hasFSQRT() &&
383  !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
384  Subtarget.hasFRE()))
386 
387  if (!Subtarget.hasFSQRT() &&
388  !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
389  Subtarget.hasFRES()))
391 
392  if (Subtarget.hasFCPSGN()) {
395  } else {
398  }
399 
400  if (Subtarget.hasFPRND()) {
405 
410  }
411 
412  // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
413  // to speed up scalar BSWAP64.
414  // CTPOP or CTTZ were introduced in P8/P9 respectively
416  if (Subtarget.hasP9Vector())
418  else
420  if (Subtarget.isISA3_0()) {
423  } else {
426  }
427 
428  if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
431  } else {
434  }
435 
436  // PowerPC does not have ROTR
439 
440  if (!Subtarget.useCRBits()) {
441  // PowerPC does not have Select
446  }
447 
448  // PowerPC wants to turn select_cc of FP into fsel when possible.
451 
452  // PowerPC wants to optimize integer setcc a bit
453  if (!Subtarget.useCRBits())
455 
456  if (Subtarget.hasFPU()) {
460 
464  }
465 
466  // PowerPC does not have BRCOND which requires SetCC
467  if (!Subtarget.useCRBits())
469 
471 
472  if (Subtarget.hasSPE()) {
473  // SPE has built-in conversions
480  } else {
481  // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
484 
485  // PowerPC does not have [U|S]INT_TO_FP
490  }
491 
492  if (Subtarget.hasDirectMove() && isPPC64) {
497  if (TM.Options.UnsafeFPMath) {
506  }
507  } else {
512  }
513 
514  // We cannot sextinreg(i1). Expand to shifts.
516 
517  // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
518  // SjLj exception handling but a light-weight setjmp/longjmp replacement to
519  // support continuation, user-level threading, and etc.. As a result, no
520  // other SjLj exception interfaces are implemented and please don't build
521  // your own exception handling based on them.
522  // LLVM/Clang supports zero-cost DWARF exception handling.
525 
526  // We want to legalize GlobalAddress and ConstantPool nodes into the
527  // appropriate instructions to materialize the address.
538 
539  // TRAP is legal.
541 
542  // TRAMPOLINE is custom lowered.
545 
546  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
548 
549  if (Subtarget.is64BitELFABI()) {
550  // VAARG always uses double-word chunks, so promote anything smaller.
560  } else if (Subtarget.is32BitELFABI()) {
561  // VAARG is custom lowered with the 32-bit SVR4 ABI.
564  } else
566 
567  // VACOPY is custom lowered with the 32-bit SVR4 ABI.
568  if (Subtarget.is32BitELFABI())
570  else
572 
573  // Use the default implementation.
583 
584  // We want to custom lower some of our intrinsics.
586 
587  // To handle counter-based loop conditions.
589 
594 
595  // Comparisons that require checking two conditions.
596  if (Subtarget.hasSPE()) {
601  }
614 
617 
618  if (Subtarget.has64BitSupport()) {
619  // They also have instructions for converting between i64 and fp.
628  // This is just the low 32 bits of a (signed) fp->i64 conversion.
629  // We cannot do this with Promote because i64 is not a legal type.
632 
633  if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
636  }
637  } else {
638  // PowerPC does not have FP_TO_UINT on 32-bit implementations.
639  if (Subtarget.hasSPE()) {
642  } else {
645  }
646  }
647 
648  // With the instructions enabled under FPCVT, we can do everything.
649  if (Subtarget.hasFPCVT()) {
650  if (Subtarget.has64BitSupport()) {
659  }
660 
669  }
670 
671  if (Subtarget.use64BitRegs()) {
672  // 64-bit PowerPC implementations can support i64 types directly
673  addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
674  // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
676  // 64-bit PowerPC wants to expand i128 shifts itself.
680  } else {
681  // 32-bit PowerPC wants to expand i64 shifts itself.
685  }
686 
687  // PowerPC has better expansions for funnel shifts than the generic
688  // TargetLowering::expandFunnelShift.
689  if (Subtarget.has64BitSupport()) {
692  }
695 
696  if (Subtarget.hasVSX()) {
701  }
702 
703  if (Subtarget.hasAltivec()) {
704  for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
709  }
710  // First set operation action for all vector types to expand. Then we
711  // will selectively turn on ones that can be effectively codegen'd.
712  for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
713  // add/sub are legal for all supported vector VT's.
716 
717  // For v2i64, these are only valid with P8Vector. This is corrected after
718  // the loop.
719  if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
724  }
725  else {
730  }
731 
732  if (Subtarget.hasVSX()) {
735  }
736 
737  // Vector instructions introduced in P8
738  if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
741  }
742  else {
745  }
746 
747  // Vector instructions introduced in P9
748  if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
750  else
752 
753  // We promote all shuffles to v16i8.
756 
757  // We promote all non-typed operations to v4i32.
773 
774  // No other operations are legal.
812 
813  for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
814  setTruncStoreAction(VT, InnerVT, Expand);
815  setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
816  setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
817  setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
818  }
819  }
821  if (!Subtarget.hasP8Vector()) {
826  }
827 
828  // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
829  // with merges, splats, etc.
831 
832  // Vector truncates to sub-word integer that fit in an Altivec/VSX register
833  // are cheap, so handle them before they get expanded to scalar.
839 
845  Subtarget.useCRBits() ? Legal : Expand);
859 
860  // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
862  // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
863  if (Subtarget.hasAltivec())
864  for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
866  // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
867  if (Subtarget.hasP8Altivec())
869 
870  addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
871  addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
872  addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
873  addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
874 
877 
878  if (Subtarget.hasVSX()) {
881  }
882 
883  if (Subtarget.hasP8Altivec())
885  else
887 
888  if (Subtarget.isISA3_1()) {
907  }
908 
911 
914 
919 
920  // Altivec does not contain unordered floating-point compare instructions
925 
926  if (Subtarget.hasVSX()) {
929  if (Subtarget.hasP8Vector()) {
932  }
933  if (Subtarget.hasDirectMove() && isPPC64) {
942  }
944 
945  // The nearbyint variants are not allowed to raise the inexact exception
946  // so we can only code-gen them with unsafe math.
947  if (TM.Options.UnsafeFPMath) {
950  }
951 
960 
966 
969 
972 
973  // Share the Altivec comparison restrictions.
978 
981 
983 
984  if (Subtarget.hasP8Vector())
985  addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
986 
987  addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
988 
989  addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
990  addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
991  addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
992 
993  if (Subtarget.hasP8Altivec()) {
997 
998  // 128 bit shifts can be accomplished via 3 instructions for SHL and
999  // SRL, but not for SRA because of the instructions available:
1000  // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
1001  // doing
1005 
1007  }
1008  else {
1012 
1014 
1015  // VSX v2i64 only supports non-arithmetic operations.
1018  }
1019 
1020  if (Subtarget.isISA3_1())
1022  else
1024 
1029 
1031 
1040 
1041  // Custom handling for partial vectors of integers converted to
1042  // floating point. We already have optimal handling for v2i32 through
1043  // the DAG combine, so those aren't necessary.
1060 
1067 
1068  if (Subtarget.hasDirectMove())
1071 
1072  // Handle constrained floating-point operations of vector.
1073  // The predictor is `hasVSX` because altivec instruction has
1074  // no exception but VSX vector instruction has.
1088 
1102 
1103  addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1104  }
1105 
1106  if (Subtarget.hasP8Altivec()) {
1107  addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1108  addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1109  }
1110 
1111  if (Subtarget.hasP9Vector()) {
1114 
1115  // 128 bit shifts can be accomplished via 3 instructions for SHL and
1116  // SRL, but not for SRA because of the instructions available:
1117  // VS{RL} and VS{RL}O.
1121 
1122  addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1128  // No extending loads to f128 on PPC.
1129  for (MVT FPT : MVT::fp_valuetypes())
1138 
1145 
1152  // No implementation for these ops for PowerPC.
1158 
1159  // Handle constrained floating-point operations of fp128
1180  } else if (Subtarget.hasAltivec() && EnableSoftFP128) {
1181  addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1182 
1183  for (MVT FPT : MVT::fp_valuetypes())
1185 
1188 
1191 
1192  // Set FADD/FSUB as libcall to avoid the legalizer to expand the
1193  // fp_to_uint and int_to_fp.
1196 
1209 
1212 
1213  // Expand the fp_extend if the target type is fp128.
1216 
1217  // Expand the fp_round if the source type is fp128.
1218  for (MVT VT : {MVT::f32, MVT::f64}) {
1221  }
1222 
1227 
1228  // Lower following f128 select_cc pattern:
1229  // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE
1231 
1232  // We need to handle f128 SELECT_CC with integer result type.
1235  }
1236 
1237  if (Subtarget.hasP9Altivec()) {
1240 
1248  }
1249 
1250  if (Subtarget.isISA3_1()) {
1253  }
1254  }
1255 
1256  if (Subtarget.pairedVectorMemops()) {
1257  addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1260  }
1261  if (Subtarget.hasMMA()) {
1262  addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1266  }
1267 
1268  if (Subtarget.has64BitSupport())
1270 
1271  if (Subtarget.isISA3_1())
1273 
1275 
1276  if (!isPPC64) {
1279  }
1280 
1282 
1283  if (Subtarget.hasAltivec()) {
1284  // Altivec instructions set fields to all zeros or all ones.
1286  }
1287 
1288  if (!isPPC64) {
1289  // These libcalls are not available in 32-bit.
1290  setLibcallName(RTLIB::SHL_I128, nullptr);
1291  setLibcallName(RTLIB::SRL_I128, nullptr);
1292  setLibcallName(RTLIB::SRA_I128, nullptr);
1293  }
1294 
1295  if (!isPPC64)
1297 
1298  setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1299 
1300  // We have target-specific dag combine patterns for the following nodes:
1309  if (Subtarget.hasFPCVT())
1314  if (Subtarget.useCRBits())
1320 
1324 
1327 
1328 
1329  if (Subtarget.useCRBits()) {
1333  }
1334 
1335  if (Subtarget.hasP9Altivec()) {
1338  }
1339 
1340  setLibcallName(RTLIB::LOG_F128, "logf128");
1341  setLibcallName(RTLIB::LOG2_F128, "log2f128");
1342  setLibcallName(RTLIB::LOG10_F128, "log10f128");
1343  setLibcallName(RTLIB::EXP_F128, "expf128");
1344  setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1345  setLibcallName(RTLIB::SIN_F128, "sinf128");
1346  setLibcallName(RTLIB::COS_F128, "cosf128");
1347  setLibcallName(RTLIB::POW_F128, "powf128");
1348  setLibcallName(RTLIB::FMIN_F128, "fminf128");
1349  setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1350  setLibcallName(RTLIB::REM_F128, "fmodf128");
1351  setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
1352  setLibcallName(RTLIB::CEIL_F128, "ceilf128");
1353  setLibcallName(RTLIB::FLOOR_F128, "floorf128");
1354  setLibcallName(RTLIB::TRUNC_F128, "truncf128");
1355  setLibcallName(RTLIB::ROUND_F128, "roundf128");
1356  setLibcallName(RTLIB::LROUND_F128, "lroundf128");
1357  setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
1358  setLibcallName(RTLIB::RINT_F128, "rintf128");
1359  setLibcallName(RTLIB::LRINT_F128, "lrintf128");
1360  setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
1361  setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
1362  setLibcallName(RTLIB::FMA_F128, "fmaf128");
1363 
1364  // With 32 condition bits, we don't need to sink (and duplicate) compares
1365  // aggressively in CodeGenPrep.
1366  if (Subtarget.useCRBits()) {
1369  }
1370 
1372 
1373  switch (Subtarget.getCPUDirective()) {
1374  default: break;
1375  case PPC::DIR_970:
1376  case PPC::DIR_A2:
1377  case PPC::DIR_E500:
1378  case PPC::DIR_E500mc:
1379  case PPC::DIR_E5500:
1380  case PPC::DIR_PWR4:
1381  case PPC::DIR_PWR5:
1382  case PPC::DIR_PWR5X:
1383  case PPC::DIR_PWR6:
1384  case PPC::DIR_PWR6X:
1385  case PPC::DIR_PWR7:
1386  case PPC::DIR_PWR8:
1387  case PPC::DIR_PWR9:
1388  case PPC::DIR_PWR10:
1389  case PPC::DIR_PWR_FUTURE:
1392  break;
1393  }
1394 
1395  if (Subtarget.enableMachineScheduler())
1397  else
1399 
1401 
1402  // The Freescale cores do better with aggressive inlining of memcpy and
1403  // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1404  if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1405  Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1406  MaxStoresPerMemset = 32;
1408  MaxStoresPerMemcpy = 32;
1410  MaxStoresPerMemmove = 32;
1412  } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1413  // The A2 also benefits from (very) aggressive inlining of memcpy and
1414  // friends. The overhead of a the function call, even when warm, can be
1415  // over one hundred cycles.
1416  MaxStoresPerMemset = 128;
1417  MaxStoresPerMemcpy = 128;
1418  MaxStoresPerMemmove = 128;
1419  MaxLoadsPerMemcmp = 128;
1420  } else {
1421  MaxLoadsPerMemcmp = 8;
1423  }
1424 
1425  IsStrictFPEnabled = true;
1426 
1427  // Let the subtarget (CPU) decide if a predictable select is more expensive
1428  // than the corresponding branch. This information is used in CGP to decide
1429  // when to convert selects into branches.
1431 }
1432 
1433 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1434 /// the desired ByVal argument alignment.
1435 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1436  if (MaxAlign == MaxMaxAlign)
1437  return;
1438  if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1439  if (MaxMaxAlign >= 32 &&
1440  VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1441  MaxAlign = Align(32);
1442  else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1443  MaxAlign < 16)
1444  MaxAlign = Align(16);
1445  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1446  Align EltAlign;
1447  getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1448  if (EltAlign > MaxAlign)
1449  MaxAlign = EltAlign;
1450  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1451  for (auto *EltTy : STy->elements()) {
1452  Align EltAlign;
1453  getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1454  if (EltAlign > MaxAlign)
1455  MaxAlign = EltAlign;
1456  if (MaxAlign == MaxMaxAlign)
1457  break;
1458  }
1459  }
1460 }
1461 
1462 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1463 /// function arguments in the caller parameter area.
1465  const DataLayout &DL) const {
1466  // 16byte and wider vectors are passed on 16byte boundary.
1467  // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1468  Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1469  if (Subtarget.hasAltivec())
1470  getMaxByValAlign(Ty, Alignment, Align(16));
1471  return Alignment.value();
1472 }
1473 
1475  return Subtarget.useSoftFloat();
1476 }
1477 
1479  return Subtarget.hasSPE();
1480 }
1481 
1483  return VT.isScalarInteger();
1484 }
1485 
1486 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1487  switch ((PPCISD::NodeType)Opcode) {
1488  case PPCISD::FIRST_NUMBER: break;
1489  case PPCISD::FSEL: return "PPCISD::FSEL";
1490  case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP";
1491  case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP";
1492  case PPCISD::FCFID: return "PPCISD::FCFID";
1493  case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
1494  case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
1495  case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
1496  case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
1497  case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
1498  case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
1499  case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
1501  return "PPCISD::FP_TO_UINT_IN_VSR,";
1503  return "PPCISD::FP_TO_SINT_IN_VSR";
1504  case PPCISD::FRE: return "PPCISD::FRE";
1505  case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
1506  case PPCISD::FTSQRT:
1507  return "PPCISD::FTSQRT";
1508  case PPCISD::FSQRT:
1509  return "PPCISD::FSQRT";
1510  case PPCISD::STFIWX: return "PPCISD::STFIWX";
1511  case PPCISD::VPERM: return "PPCISD::VPERM";
1512  case PPCISD::XXSPLT: return "PPCISD::XXSPLT";
1514  return "PPCISD::XXSPLTI_SP_TO_DP";
1515  case PPCISD::XXSPLTI32DX:
1516  return "PPCISD::XXSPLTI32DX";
1517  case PPCISD::VECINSERT: return "PPCISD::VECINSERT";
1518  case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI";
1519  case PPCISD::VECSHL: return "PPCISD::VECSHL";
1520  case PPCISD::CMPB: return "PPCISD::CMPB";
1521  case PPCISD::Hi: return "PPCISD::Hi";
1522  case PPCISD::Lo: return "PPCISD::Lo";
1523  case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
1524  case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1525  case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1526  case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
1527  case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET";
1528  case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA";
1529  case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
1530  case PPCISD::SRL: return "PPCISD::SRL";
1531  case PPCISD::SRA: return "PPCISD::SRA";
1532  case PPCISD::SHL: return "PPCISD::SHL";
1533  case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE";
1534  case PPCISD::CALL: return "PPCISD::CALL";
1535  case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
1536  case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC";
1537  case PPCISD::MTCTR: return "PPCISD::MTCTR";
1538  case PPCISD::BCTRL: return "PPCISD::BCTRL";
1539  case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
1540  case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
1541  case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
1542  case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
1543  case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1544  case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
1545  case PPCISD::MFVSR: return "PPCISD::MFVSR";
1546  case PPCISD::MTVSRA: return "PPCISD::MTVSRA";
1547  case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ";
1548  case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP";
1549  case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP";
1551  return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1553  return "PPCISD::ANDI_rec_1_EQ_BIT";
1555  return "PPCISD::ANDI_rec_1_GT_BIT";
1556  case PPCISD::VCMP: return "PPCISD::VCMP";
1557  case PPCISD::VCMP_rec: return "PPCISD::VCMP_rec";
1558  case PPCISD::LBRX: return "PPCISD::LBRX";
1559  case PPCISD::STBRX: return "PPCISD::STBRX";
1560  case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
1561  case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
1562  case PPCISD::LXSIZX: return "PPCISD::LXSIZX";
1563  case PPCISD::STXSIX: return "PPCISD::STXSIX";
1564  case PPCISD::VEXTS: return "PPCISD::VEXTS";
1565  case PPCISD::LXVD2X: return "PPCISD::LXVD2X";
1566  case PPCISD::STXVD2X: return "PPCISD::STXVD2X";
1567  case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE";
1568  case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE";
1570  return "PPCISD::ST_VSR_SCAL_INT";
1571  case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
1572  case PPCISD::BDNZ: return "PPCISD::BDNZ";
1573  case PPCISD::BDZ: return "PPCISD::BDZ";
1574  case PPCISD::MFFS: return "PPCISD::MFFS";
1575  case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
1576  case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
1577  case PPCISD::CR6SET: return "PPCISD::CR6SET";
1578  case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
1579  case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
1580  case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT";
1581  case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1582  case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
1583  case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
1584  case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
1585  case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
1586  case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
1587  case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1588  case PPCISD::TLSGD_AIX: return "PPCISD::TLSGD_AIX";
1589  case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
1590  case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
1591  case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
1592  case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1593  case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1594  case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
1595  case PPCISD::PADDI_DTPREL:
1596  return "PPCISD::PADDI_DTPREL";
1597  case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
1598  case PPCISD::SC: return "PPCISD::SC";
1599  case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB";
1600  case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE";
1601  case PPCISD::RFEBB: return "PPCISD::RFEBB";
1602  case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD";
1603  case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN";
1604  case PPCISD::VABSD: return "PPCISD::VABSD";
1605  case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128";
1606  case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64";
1607  case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE";
1608  case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI";
1609  case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH";
1610  case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF";
1611  case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR";
1613  return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1615  return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1616  case PPCISD::ACC_BUILD: return "PPCISD::ACC_BUILD";
1617  case PPCISD::PAIR_BUILD: return "PPCISD::PAIR_BUILD";
1618  case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1619  case PPCISD::XXMFACC: return "PPCISD::XXMFACC";
1620  case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT";
1621  case PPCISD::FNMSUB: return "PPCISD::FNMSUB";
1623  return "PPCISD::STRICT_FADDRTZ";
1624  case PPCISD::STRICT_FCTIDZ:
1625  return "PPCISD::STRICT_FCTIDZ";
1626  case PPCISD::STRICT_FCTIWZ:
1627  return "PPCISD::STRICT_FCTIWZ";
1629  return "PPCISD::STRICT_FCTIDUZ";
1631  return "PPCISD::STRICT_FCTIWUZ";
1632  case PPCISD::STRICT_FCFID:
1633  return "PPCISD::STRICT_FCFID";
1634  case PPCISD::STRICT_FCFIDU:
1635  return "PPCISD::STRICT_FCFIDU";
1636  case PPCISD::STRICT_FCFIDS:
1637  return "PPCISD::STRICT_FCFIDS";
1639  return "PPCISD::STRICT_FCFIDUS";
1640  case PPCISD::LXVRZX: return "PPCISD::LXVRZX";
1641  }
1642  return nullptr;
1643 }
1644 
1646  EVT VT) const {
1647  if (!VT.isVector())
1648  return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1649 
1651 }
1652 
1654  assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1655  return true;
1656 }
1657 
1658 //===----------------------------------------------------------------------===//
1659 // Node matching predicates, for use by the tblgen matching code.
1660 //===----------------------------------------------------------------------===//
1661 
1662 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1664  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1665  return CFP->getValueAPF().isZero();
1666  else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1667  // Maybe this has already been legalized into the constant pool?
1668  if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1669  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1670  return CFP->getValueAPF().isZero();
1671  }
1672  return false;
1673 }
1674 
1675 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1676 /// true if Op is undef or if it matches the specified value.
1677 static bool isConstantOrUndef(int Op, int Val) {
1678  return Op < 0 || Op == Val;
1679 }
1680 
1681 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1682 /// VPKUHUM instruction.
1683 /// The ShuffleKind distinguishes between big-endian operations with
1684 /// two different inputs (0), either-endian operations with two identical
1685 /// inputs (1), and little-endian operations with two different inputs (2).
1686 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1688  SelectionDAG &DAG) {
1689  bool IsLE = DAG.getDataLayout().isLittleEndian();
1690  if (ShuffleKind == 0) {
1691  if (IsLE)
1692  return false;
1693  for (unsigned i = 0; i != 16; ++i)
1694  if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1695  return false;
1696  } else if (ShuffleKind == 2) {
1697  if (!IsLE)
1698  return false;
1699  for (unsigned i = 0; i != 16; ++i)
1700  if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1701  return false;
1702  } else if (ShuffleKind == 1) {
1703  unsigned j = IsLE ? 0 : 1;
1704  for (unsigned i = 0; i != 8; ++i)
1705  if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1706  !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1707  return false;
1708  }
1709  return true;
1710 }
1711 
1712 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1713 /// VPKUWUM instruction.
1714 /// The ShuffleKind distinguishes between big-endian operations with
1715 /// two different inputs (0), either-endian operations with two identical
1716 /// inputs (1), and little-endian operations with two different inputs (2).
1717 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1719  SelectionDAG &DAG) {
1720  bool IsLE = DAG.getDataLayout().isLittleEndian();
1721  if (ShuffleKind == 0) {
1722  if (IsLE)
1723  return false;
1724  for (unsigned i = 0; i != 16; i += 2)
1725  if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1726  !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1727  return false;
1728  } else if (ShuffleKind == 2) {
1729  if (!IsLE)
1730  return false;
1731  for (unsigned i = 0; i != 16; i += 2)
1732  if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1733  !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1734  return false;
1735  } else if (ShuffleKind == 1) {
1736  unsigned j = IsLE ? 0 : 2;
1737  for (unsigned i = 0; i != 8; i += 2)
1738  if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1739  !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1740  !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1741  !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1742  return false;
1743  }
1744  return true;
1745 }
1746 
1747 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1748 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1749 /// current subtarget.
1750 ///
1751 /// The ShuffleKind distinguishes between big-endian operations with
1752 /// two different inputs (0), either-endian operations with two identical
1753 /// inputs (1), and little-endian operations with two different inputs (2).
1754 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1756  SelectionDAG &DAG) {
1757  const PPCSubtarget& Subtarget =
1758  static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1759  if (!Subtarget.hasP8Vector())
1760  return false;
1761 
1762  bool IsLE = DAG.getDataLayout().isLittleEndian();
1763  if (ShuffleKind == 0) {
1764  if (IsLE)
1765  return false;
1766  for (unsigned i = 0; i != 16; i += 4)
1767  if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) ||
1768  !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) ||
1769  !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) ||
1770  !isConstantOrUndef(N->getMaskElt(i+3), i*2+7))
1771  return false;
1772  } else if (ShuffleKind == 2) {
1773  if (!IsLE)
1774  return false;
1775  for (unsigned i = 0; i != 16; i += 4)
1776  if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1777  !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) ||
1778  !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) ||
1779  !isConstantOrUndef(N->getMaskElt(i+3), i*2+3))
1780  return false;
1781  } else if (ShuffleKind == 1) {
1782  unsigned j = IsLE ? 0 : 4;
1783  for (unsigned i = 0; i != 8; i += 4)
1784  if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1785  !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1786  !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) ||
1787  !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) ||
1788  !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1789  !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) ||
1790  !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1791  !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1792  return false;
1793  }
1794  return true;
1795 }
1796 
1797 /// isVMerge - Common function, used to match vmrg* shuffles.
1798 ///
1799 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1800  unsigned LHSStart, unsigned RHSStart) {
1801  if (N->getValueType(0) != MVT::v16i8)
1802  return false;
1803  assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1804  "Unsupported merge size!");
1805 
1806  for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
1807  for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
1808  if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1809  LHSStart+j+i*UnitSize) ||
1810  !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1811  RHSStart+j+i*UnitSize))
1812  return false;
1813  }
1814  return true;
1815 }
1816 
1817 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1818 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1819 /// The ShuffleKind distinguishes between big-endian merges with two
1820 /// different inputs (0), either-endian merges with two identical inputs (1),
1821 /// and little-endian merges with two different inputs (2). For the latter,
1822 /// the input operands are swapped (see PPCInstrAltivec.td).
1824  unsigned ShuffleKind, SelectionDAG &DAG) {
1825  if (DAG.getDataLayout().isLittleEndian()) {
1826  if (ShuffleKind == 1) // unary
1827  return isVMerge(N, UnitSize, 0, 0);
1828  else if (ShuffleKind == 2) // swapped
1829  return isVMerge(N, UnitSize, 0, 16);
1830  else
1831  return false;
1832  } else {
1833  if (ShuffleKind == 1) // unary
1834  return isVMerge(N, UnitSize, 8, 8);
1835  else if (ShuffleKind == 0) // normal
1836  return isVMerge(N, UnitSize, 8, 24);
1837  else
1838  return false;
1839  }
1840 }
1841 
1842 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1843 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1844 /// The ShuffleKind distinguishes between big-endian merges with two
1845 /// different inputs (0), either-endian merges with two identical inputs (1),
1846 /// and little-endian merges with two different inputs (2). For the latter,
1847 /// the input operands are swapped (see PPCInstrAltivec.td).
1849  unsigned ShuffleKind, SelectionDAG &DAG) {
1850  if (DAG.getDataLayout().isLittleEndian()) {
1851  if (ShuffleKind == 1) // unary
1852  return isVMerge(N, UnitSize, 8, 8);
1853  else if (ShuffleKind == 2) // swapped
1854  return isVMerge(N, UnitSize, 8, 24);
1855  else
1856  return false;
1857  } else {
1858  if (ShuffleKind == 1) // unary
1859  return isVMerge(N, UnitSize, 0, 0);
1860  else if (ShuffleKind == 0) // normal
1861  return isVMerge(N, UnitSize, 0, 16);
1862  else
1863  return false;
1864  }
1865 }
1866 
1867 /**
1868  * Common function used to match vmrgew and vmrgow shuffles
1869  *
1870  * The indexOffset determines whether to look for even or odd words in
1871  * the shuffle mask. This is based on the of the endianness of the target
1872  * machine.
1873  * - Little Endian:
1874  * - Use offset of 0 to check for odd elements
1875  * - Use offset of 4 to check for even elements
1876  * - Big Endian:
1877  * - Use offset of 0 to check for even elements
1878  * - Use offset of 4 to check for odd elements
1879  * A detailed description of the vector element ordering for little endian and
1880  * big endian can be found at
1881  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1882  * Targeting your applications - what little endian and big endian IBM XL C/C++
1883  * compiler differences mean to you
1884  *
1885  * The mask to the shuffle vector instruction specifies the indices of the
1886  * elements from the two input vectors to place in the result. The elements are
1887  * numbered in array-access order, starting with the first vector. These vectors
1888  * are always of type v16i8, thus each vector will contain 16 elements of size
1889  * 8. More info on the shuffle vector can be found in the
1890  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1891  * Language Reference.
1892  *
1893  * The RHSStartValue indicates whether the same input vectors are used (unary)
1894  * or two different input vectors are used, based on the following:
1895  * - If the instruction uses the same vector for both inputs, the range of the
1896  * indices will be 0 to 15. In this case, the RHSStart value passed should
1897  * be 0.
1898  * - If the instruction has two different vectors then the range of the
1899  * indices will be 0 to 31. In this case, the RHSStart value passed should
1900  * be 16 (indices 0-15 specify elements in the first vector while indices 16
1901  * to 31 specify elements in the second vector).
1902  *
1903  * \param[in] N The shuffle vector SD Node to analyze
1904  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1905  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1906  * vector to the shuffle_vector instruction
1907  * \return true iff this shuffle vector represents an even or odd word merge
1908  */
1909 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1910  unsigned RHSStartValue) {
1911  if (N->getValueType(0) != MVT::v16i8)
1912  return false;
1913 
1914  for (unsigned i = 0; i < 2; ++i)
1915  for (unsigned j = 0; j < 4; ++j)
1916  if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1917  i*RHSStartValue+j+IndexOffset) ||
1918  !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1919  i*RHSStartValue+j+IndexOffset+8))
1920  return false;
1921  return true;
1922 }
1923 
1924 /**
1925  * Determine if the specified shuffle mask is suitable for the vmrgew or
1926  * vmrgow instructions.
1927  *
1928  * \param[in] N The shuffle vector SD Node to analyze
1929  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1930  * \param[in] ShuffleKind Identify the type of merge:
1931  * - 0 = big-endian merge with two different inputs;
1932  * - 1 = either-endian merge with two identical inputs;
1933  * - 2 = little-endian merge with two different inputs (inputs are swapped for
1934  * little-endian merges).
1935  * \param[in] DAG The current SelectionDAG
1936  * \return true iff this shuffle mask
1937  */
1939  unsigned ShuffleKind, SelectionDAG &DAG) {
1940  if (DAG.getDataLayout().isLittleEndian()) {
1941  unsigned indexOffset = CheckEven ? 4 : 0;
1942  if (ShuffleKind == 1) // Unary
1943  return isVMerge(N, indexOffset, 0);
1944  else if (ShuffleKind == 2) // swapped
1945  return isVMerge(N, indexOffset, 16);
1946  else
1947  return false;
1948  }
1949  else {
1950  unsigned indexOffset = CheckEven ? 0 : 4;
1951  if (ShuffleKind == 1) // Unary
1952  return isVMerge(N, indexOffset, 0);
1953  else if (ShuffleKind == 0) // Normal
1954  return isVMerge(N, indexOffset, 16);
1955  else
1956  return false;
1957  }
1958  return false;
1959 }
1960 
1961 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1962 /// amount, otherwise return -1.
1963 /// The ShuffleKind distinguishes between big-endian operations with two
1964 /// different inputs (0), either-endian operations with two identical inputs
1965 /// (1), and little-endian operations with two different inputs (2). For the
1966 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1967 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1968  SelectionDAG &DAG) {
1969  if (N->getValueType(0) != MVT::v16i8)
1970  return -1;
1971 
1972  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1973 
1974  // Find the first non-undef value in the shuffle mask.
1975  unsigned i;
1976  for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1977  /*search*/;
1978 
1979  if (i == 16) return -1; // all undef.
1980 
1981  // Otherwise, check to see if the rest of the elements are consecutively
1982  // numbered from this value.
1983  unsigned ShiftAmt = SVOp->getMaskElt(i);
1984  if (ShiftAmt < i) return -1;
1985 
1986  ShiftAmt -= i;
1987  bool isLE = DAG.getDataLayout().isLittleEndian();
1988 
1989  if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1990  // Check the rest of the elements to see if they are consecutive.
1991  for (++i; i != 16; ++i)
1992  if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1993  return -1;
1994  } else if (ShuffleKind == 1) {
1995  // Check the rest of the elements to see if they are consecutive.
1996  for (++i; i != 16; ++i)
1997  if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1998  return -1;
1999  } else
2000  return -1;
2001 
2002  if (isLE)
2003  ShiftAmt = 16 - ShiftAmt;
2004 
2005  return ShiftAmt;
2006 }
2007 
2008 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
2009 /// specifies a splat of a single element that is suitable for input to
2010 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
2012  assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
2013  EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
2014 
2015  // The consecutive indices need to specify an element, not part of two
2016  // different elements. So abandon ship early if this isn't the case.
2017  if (N->getMaskElt(0) % EltSize != 0)
2018  return false;
2019 
2020  // This is a splat operation if each element of the permute is the same, and
2021  // if the value doesn't reference the second vector.
2022  unsigned ElementBase = N->getMaskElt(0);
2023 
2024  // FIXME: Handle UNDEF elements too!
2025  if (ElementBase >= 16)
2026  return false;
2027 
2028  // Check that the indices are consecutive, in the case of a multi-byte element
2029  // splatted with a v16i8 mask.
2030  for (unsigned i = 1; i != EltSize; ++i)
2031  if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2032  return false;
2033 
2034  for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2035  if (N->getMaskElt(i) < 0) continue;
2036  for (unsigned j = 0; j != EltSize; ++j)
2037  if (N->getMaskElt(i+j) != N->getMaskElt(j))
2038  return false;
2039  }
2040  return true;
2041 }
2042 
2043 /// Check that the mask is shuffling N byte elements. Within each N byte
2044 /// element of the mask, the indices could be either in increasing or
2045 /// decreasing order as long as they are consecutive.
2046 /// \param[in] N the shuffle vector SD Node to analyze
2047 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2048 /// Word/DoubleWord/QuadWord).
2049 /// \param[in] StepLen the delta indices number among the N byte element, if
2050 /// the mask is in increasing/decreasing order then it is 1/-1.
2051 /// \return true iff the mask is shuffling N byte elements.
2053  int StepLen) {
2054  assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
2055  "Unexpected element width.");
2056  assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2057 
2058  unsigned NumOfElem = 16 / Width;
2059  unsigned MaskVal[16]; // Width is never greater than 16
2060  for (unsigned i = 0; i < NumOfElem; ++i) {
2061  MaskVal[0] = N->getMaskElt(i * Width);
2062  if ((StepLen == 1) && (MaskVal[0] % Width)) {
2063  return false;
2064  } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2065  return false;
2066  }
2067 
2068  for (unsigned int j = 1; j < Width; ++j) {
2069  MaskVal[j] = N->getMaskElt(i * Width + j);
2070  if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2071  return false;
2072  }
2073  }
2074  }
2075 
2076  return true;
2077 }
2078 
2079 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2080  unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2081  if (!isNByteElemShuffleMask(N, 4, 1))
2082  return false;
2083 
2084  // Now we look at mask elements 0,4,8,12
2085  unsigned M0 = N->getMaskElt(0) / 4;
2086  unsigned M1 = N->getMaskElt(4) / 4;
2087  unsigned M2 = N->getMaskElt(8) / 4;
2088  unsigned M3 = N->getMaskElt(12) / 4;
2089  unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2090  unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2091 
2092  // Below, let H and L be arbitrary elements of the shuffle mask
2093  // where H is in the range [4,7] and L is in the range [0,3].
2094  // H, 1, 2, 3 or L, 5, 6, 7
2095  if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2096  (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2097  ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2098  InsertAtByte = IsLE ? 12 : 0;
2099  Swap = M0 < 4;
2100  return true;
2101  }
2102  // 0, H, 2, 3 or 4, L, 6, 7
2103  if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2104  (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2105  ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2106  InsertAtByte = IsLE ? 8 : 4;
2107  Swap = M1 < 4;
2108  return true;
2109  }
2110  // 0, 1, H, 3 or 4, 5, L, 7
2111  if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2112  (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2113  ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2114  InsertAtByte = IsLE ? 4 : 8;
2115  Swap = M2 < 4;
2116  return true;
2117  }
2118  // 0, 1, 2, H or 4, 5, 6, L
2119  if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2120  (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2121  ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2122  InsertAtByte = IsLE ? 0 : 12;
2123  Swap = M3 < 4;
2124  return true;
2125  }
2126 
2127  // If both vector operands for the shuffle are the same vector, the mask will
2128  // contain only elements from the first one and the second one will be undef.
2129  if (N->getOperand(1).isUndef()) {
2130  ShiftElts = 0;
2131  Swap = true;
2132  unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2133  if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2134  InsertAtByte = IsLE ? 12 : 0;
2135  return true;
2136  }
2137  if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2138  InsertAtByte = IsLE ? 8 : 4;
2139  return true;
2140  }
2141  if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2142  InsertAtByte = IsLE ? 4 : 8;
2143  return true;
2144  }
2145  if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2146  InsertAtByte = IsLE ? 0 : 12;
2147  return true;
2148  }
2149  }
2150 
2151  return false;
2152 }
2153 
2155  bool &Swap, bool IsLE) {
2156  assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2157  // Ensure each byte index of the word is consecutive.
2158  if (!isNByteElemShuffleMask(N, 4, 1))
2159  return false;
2160 
2161  // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2162  unsigned M0 = N->getMaskElt(0) / 4;
2163  unsigned M1 = N->getMaskElt(4) / 4;
2164  unsigned M2 = N->getMaskElt(8) / 4;
2165  unsigned M3 = N->getMaskElt(12) / 4;
2166 
2167  // If both vector operands for the shuffle are the same vector, the mask will
2168  // contain only elements from the first one and the second one will be undef.
2169  if (N->getOperand(1).isUndef()) {
2170  assert(M0 < 4 && "Indexing into an undef vector?");
2171  if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2172  return false;
2173 
2174  ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2175  Swap = false;
2176  return true;
2177  }
2178 
2179  // Ensure each word index of the ShuffleVector Mask is consecutive.
2180  if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2181  return false;
2182 
2183  if (IsLE) {
2184  if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2185  // Input vectors don't need to be swapped if the leading element
2186  // of the result is one of the 3 left elements of the second vector
2187  // (or if there is no shift to be done at all).
2188  Swap = false;
2189  ShiftElts = (8 - M0) % 8;
2190  } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2191  // Input vectors need to be swapped if the leading element
2192  // of the result is one of the 3 left elements of the first vector
2193  // (or if we're shifting by 4 - thereby simply swapping the vectors).
2194  Swap = true;
2195  ShiftElts = (4 - M0) % 4;
2196  }
2197 
2198  return true;
2199  } else { // BE
2200  if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2201  // Input vectors don't need to be swapped if the leading element
2202  // of the result is one of the 4 elements of the first vector.
2203  Swap = false;
2204  ShiftElts = M0;
2205  } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2206  // Input vectors need to be swapped if the leading element
2207  // of the result is one of the 4 elements of the right vector.
2208  Swap = true;
2209  ShiftElts = M0 - 4;
2210  }
2211 
2212  return true;
2213  }
2214 }
2215 
2217  assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2218 
2219  if (!isNByteElemShuffleMask(N, Width, -1))
2220  return false;
2221 
2222  for (int i = 0; i < 16; i += Width)
2223  if (N->getMaskElt(i) != i + Width - 1)
2224  return false;
2225 
2226  return true;
2227 }
2228 
2230  return isXXBRShuffleMaskHelper(N, 2);
2231 }
2232 
2234  return isXXBRShuffleMaskHelper(N, 4);
2235 }
2236 
2238  return isXXBRShuffleMaskHelper(N, 8);
2239 }
2240 
2242  return isXXBRShuffleMaskHelper(N, 16);
2243 }
2244 
2245 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2246 /// if the inputs to the instruction should be swapped and set \p DM to the
2247 /// value for the immediate.
2248 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2249 /// AND element 0 of the result comes from the first input (LE) or second input
2250 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2251 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2252 /// mask.
2254  bool &Swap, bool IsLE) {
2255  assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2256 
2257  // Ensure each byte index of the double word is consecutive.
2258  if (!isNByteElemShuffleMask(N, 8, 1))
2259  return false;
2260 
2261  unsigned M0 = N->getMaskElt(0) / 8;
2262  unsigned M1 = N->getMaskElt(8) / 8;
2263  assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2264 
2265  // If both vector operands for the shuffle are the same vector, the mask will
2266  // contain only elements from the first one and the second one will be undef.
2267  if (N->getOperand(1).isUndef()) {
2268  if ((M0 | M1) < 2) {
2269  DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2270  Swap = false;
2271  return true;
2272  } else
2273  return false;
2274  }
2275 
2276  if (IsLE) {
2277  if (M0 > 1 && M1 < 2) {
2278  Swap = false;
2279  } else if (M0 < 2 && M1 > 1) {
2280  M0 = (M0 + 2) % 4;
2281  M1 = (M1 + 2) % 4;
2282  Swap = true;
2283  } else
2284  return false;
2285 
2286  // Note: if control flow comes here that means Swap is already set above
2287  DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2288  return true;
2289  } else { // BE
2290  if (M0 < 2 && M1 > 1) {
2291  Swap = false;
2292  } else if (M0 > 1 && M1 < 2) {
2293  M0 = (M0 + 2) % 4;
2294  M1 = (M1 + 2) % 4;
2295  Swap = true;
2296  } else
2297  return false;
2298 
2299  // Note: if control flow comes here that means Swap is already set above
2300  DM = (M0 << 1) + (M1 & 1);
2301  return true;
2302  }
2303 }
2304 
2305 
2306 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2307 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2308 /// elements are counted from the left of the vector register).
2309 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2310  SelectionDAG &DAG) {
2311  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2312  assert(isSplatShuffleMask(SVOp, EltSize));
2313  if (DAG.getDataLayout().isLittleEndian())
2314  return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2315  else
2316  return SVOp->getMaskElt(0) / EltSize;
2317 }
2318 
2319 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2320 /// by using a vspltis[bhw] instruction of the specified element size, return
2321 /// the constant being splatted. The ByteSize field indicates the number of
2322 /// bytes of each element [124] -> [bhw].
2323 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2324  SDValue OpVal(nullptr, 0);
2325 
2326  // If ByteSize of the splat is bigger than the element size of the
2327  // build_vector, then we have a case where we are checking for a splat where
2328  // multiple elements of the buildvector are folded together into a single
2329  // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2330  unsigned EltSize = 16/N->getNumOperands();
2331  if (EltSize < ByteSize) {
2332  unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
2333  SDValue UniquedVals[4];
2334  assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2335 
2336  // See if all of the elements in the buildvector agree across.
2337  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2338  if (N->getOperand(i).isUndef()) continue;
2339  // If the element isn't a constant, bail fully out.
2340  if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2341 
2342  if (!UniquedVals[i&(Multiple-1)].getNode())
2343  UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2344  else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2345  return SDValue(); // no match.
2346  }
2347 
2348  // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2349  // either constant or undef values that are identical for each chunk. See
2350  // if these chunks can form into a larger vspltis*.
2351 
2352  // Check to see if all of the leading entries are either 0 or -1. If
2353  // neither, then this won't fit into the immediate field.
2354  bool LeadingZero = true;
2355  bool LeadingOnes = true;
2356  for (unsigned i = 0; i != Multiple-1; ++i) {
2357  if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
2358 
2359  LeadingZero &= isNullConstant(UniquedVals[i]);
2360  LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2361  }
2362  // Finally, check the least significant entry.
2363  if (LeadingZero) {
2364  if (!UniquedVals[Multiple-1].getNode())
2365  return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
2366  int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2367  if (Val < 16) // 0,0,0,4 -> vspltisw(4)
2368  return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2369  }
2370  if (LeadingOnes) {
2371  if (!UniquedVals[Multiple-1].getNode())
2372  return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2373  int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2374  if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
2375  return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2376  }
2377 
2378  return SDValue();
2379  }
2380 
2381  // Check to see if this buildvec has a single non-undef value in its elements.
2382  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2383  if (N->getOperand(i).isUndef()) continue;
2384  if (!OpVal.getNode())
2385  OpVal = N->getOperand(i);
2386  else if (OpVal != N->getOperand(i))
2387  return SDValue();
2388  }
2389 
2390  if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
2391 
2392  unsigned ValSizeInBytes = EltSize;
2393  uint64_t Value = 0;
2394  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2395  Value = CN->getZExtValue();
2396  } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2397  assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2398  Value = FloatToBits(CN->getValueAPF().convertToFloat());
2399  }
2400 
2401  // If the splat value is larger than the element value, then we can never do
2402  // this splat. The only case that we could fit the replicated bits into our
2403  // immediate field for would be zero, and we prefer to use vxor for it.
2404  if (ValSizeInBytes < ByteSize) return SDValue();
2405 
2406  // If the element value is larger than the splat value, check if it consists
2407  // of a repeated bit pattern of size ByteSize.
2408  if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2409  return SDValue();
2410 
2411  // Properly sign extend the value.
2412  int MaskVal = SignExtend32(Value, ByteSize * 8);
2413 
2414  // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2415  if (MaskVal == 0) return SDValue();
2416 
2417  // Finally, if this value fits in a 5 bit sext field, return it
2418  if (SignExtend32<5>(MaskVal) == MaskVal)
2419  return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2420  return SDValue();
2421 }
2422 
2423 //===----------------------------------------------------------------------===//
2424 // Addressing Mode Selection
2425 //===----------------------------------------------------------------------===//
2426 
2427 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2428 /// or 64-bit immediate, and if the value can be accurately represented as a
2429 /// sign extension from a 16-bit value. If so, this returns true and the
2430 /// immediate.
2431 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2432  if (!isa<ConstantSDNode>(N))
2433  return false;
2434 
2435  Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2436  if (N->getValueType(0) == MVT::i32)
2437  return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2438  else
2439  return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2440 }
2441 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2442  return isIntS16Immediate(Op.getNode(), Imm);
2443 }
2444 
2445 
2446 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2447 /// be represented as an indexed [r+r] operation.
2449  SDValue &Index,
2450  SelectionDAG &DAG) const {
2451  for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2452  UI != E; ++UI) {
2453  if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2454  if (Memop->getMemoryVT() == MVT::f64) {
2455  Base = N.getOperand(0);
2456  Index = N.getOperand(1);
2457  return true;
2458  }
2459  }
2460  }
2461  return false;
2462 }
2463 
2464 /// isIntS34Immediate - This method tests if value of node given can be
2465 /// accurately represented as a sign extension from a 34-bit value. If so,
2466 /// this returns true and the immediate.
2467 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2468  if (!isa<ConstantSDNode>(N))
2469  return false;
2470 
2471  Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2472  return isInt<34>(Imm);
2473 }
2474 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) {
2475  return isIntS34Immediate(Op.getNode(), Imm);
2476 }
2477 
2478 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2479 /// can be represented as an indexed [r+r] operation. Returns false if it
2480 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2481 /// non-zero and N can be represented by a base register plus a signed 16-bit
2482 /// displacement, make a more precise judgement by checking (displacement % \p
2483 /// EncodingAlignment).
2485  SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2486  MaybeAlign EncodingAlignment) const {
2487  // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2488  // a [pc+imm].
2489  if (SelectAddressPCRel(N, Base))
2490  return false;
2491 
2492  int16_t Imm = 0;
2493  if (N.getOpcode() == ISD::ADD) {
2494  // Is there any SPE load/store (f64), which can't handle 16bit offset?
2495  // SPE load/store can only handle 8-bit offsets.
2496  if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2497  return true;
2498  if (isIntS16Immediate(N.getOperand(1), Imm) &&
2499  (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2500  return false; // r+i
2501  if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2502  return false; // r+i
2503 
2504  Base = N.getOperand(0);
2505  Index = N.getOperand(1);
2506  return true;
2507  } else if (N.getOpcode() == ISD::OR) {
2508  if (isIntS16Immediate(N.getOperand(1), Imm) &&
2509  (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2510  return false; // r+i can fold it if we can.
2511 
2512  // If this is an or of disjoint bitfields, we can codegen this as an add
2513  // (for better address arithmetic) if the LHS and RHS of the OR are provably
2514  // disjoint.
2515  KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2516 
2517  if (LHSKnown.Zero.getBoolValue()) {
2518  KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2519  // If all of the bits are known zero on the LHS or RHS, the add won't
2520  // carry.
2521  if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2522  Base = N.getOperand(0);
2523  Index = N.getOperand(1);
2524  return true;
2525  }
2526  }
2527  }
2528 
2529  return false;
2530 }
2531 
2532 // If we happen to be doing an i64 load or store into a stack slot that has
2533 // less than a 4-byte alignment, then the frame-index elimination may need to
2534 // use an indexed load or store instruction (because the offset may not be a
2535 // multiple of 4). The extra register needed to hold the offset comes from the
2536 // register scavenger, and it is possible that the scavenger will need to use
2537 // an emergency spill slot. As a result, we need to make sure that a spill slot
2538 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2539 // stack slot.
2540 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2541  // FIXME: This does not handle the LWA case.
2542  if (VT != MVT::i64)
2543  return;
2544 
2545  // NOTE: We'll exclude negative FIs here, which come from argument
2546  // lowering, because there are no known test cases triggering this problem
2547  // using packed structures (or similar). We can remove this exclusion if
2548  // we find such a test case. The reason why this is so test-case driven is
2549  // because this entire 'fixup' is only to prevent crashes (from the
2550  // register scavenger) on not-really-valid inputs. For example, if we have:
2551  // %a = alloca i1
2552  // %b = bitcast i1* %a to i64*
2553  // store i64* a, i64 b
2554  // then the store should really be marked as 'align 1', but is not. If it
2555  // were marked as 'align 1' then the indexed form would have been
2556  // instruction-selected initially, and the problem this 'fixup' is preventing
2557  // won't happen regardless.
2558  if (FrameIdx < 0)
2559  return;
2560 
2561  MachineFunction &MF = DAG.getMachineFunction();
2562  MachineFrameInfo &MFI = MF.getFrameInfo();
2563 
2564  if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2565  return;
2566 
2567  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2568  FuncInfo->setHasNonRISpills();
2569 }
2570 
2571 /// Returns true if the address N can be represented by a base register plus
2572 /// a signed 16-bit displacement [r+imm], and if it is not better
2573 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept
2574 /// displacements that are multiples of that value.
2576  SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2577  MaybeAlign EncodingAlignment) const {
2578  // FIXME dl should come from parent load or store, not from address
2579  SDLoc dl(N);
2580 
2581  // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2582  // a [pc+imm].
2583  if (SelectAddressPCRel(N, Base))
2584  return false;
2585 
2586  // If this can be more profitably realized as r+r, fail.
2587  if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2588  return false;
2589 
2590  if (N.getOpcode() == ISD::ADD) {
2591  int16_t imm = 0;
2592  if (isIntS16Immediate(N.getOperand(1), imm) &&
2593  (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2594  Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2595  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2596  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2597  fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2598  } else {
2599  Base = N.getOperand(0);
2600  }
2601  return true; // [r+i]
2602  } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2603  // Match LOAD (ADD (X, Lo(G))).
2604  assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2605  && "Cannot handle constant offsets yet!");
2606  Disp = N.getOperand(1).getOperand(0); // The global address.
2609  Disp.getOpcode() == ISD::TargetConstantPool ||
2610  Disp.getOpcode() == ISD::TargetJumpTable);
2611  Base = N.getOperand(0);
2612  return true; // [&g+r]
2613  }
2614  } else if (N.getOpcode() == ISD::OR) {
2615  int16_t imm = 0;
2616  if (isIntS16Immediate(N.getOperand(1), imm) &&
2617  (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2618  // If this is an or of disjoint bitfields, we can codegen this as an add
2619  // (for better address arithmetic) if the LHS and RHS of the OR are
2620  // provably disjoint.
2621  KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2622 
2623  if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2624  // If all of the bits are known zero on the LHS or RHS, the add won't
2625  // carry.
2626  if (FrameIndexSDNode *FI =
2627  dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2628  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2629  fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2630  } else {
2631  Base = N.getOperand(0);
2632  }
2633  Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2634  return true;
2635  }
2636  }
2637  } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2638  // Loading from a constant address.
2639 
2640  // If this address fits entirely in a 16-bit sext immediate field, codegen
2641  // this as "d, 0"
2642  int16_t Imm;
2643  if (isIntS16Immediate(CN, Imm) &&
2644  (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2645  Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2646  Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2647  CN->getValueType(0));
2648  return true;
2649  }
2650 
2651  // Handle 32-bit sext immediates with LIS + addr mode.
2652  if ((CN->getValueType(0) == MVT::i32 ||
2653  (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2654  (!EncodingAlignment ||
2655  isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2656  int Addr = (int)CN->getZExtValue();
2657 
2658  // Otherwise, break this down into an LIS + disp.
2659  Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2660 
2661  Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2662  MVT::i32);
2663  unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2664  Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2665  return true;
2666  }
2667  }
2668 
2669  Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2670  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2671  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2672  fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2673  } else
2674  Base = N;
2675  return true; // [r+0]
2676 }
2677 
2678 /// Similar to the 16-bit case but for instructions that take a 34-bit
2679 /// displacement field (prefixed loads/stores).
2681  SDValue &Base,
2682  SelectionDAG &DAG) const {
2683  // Only on 64-bit targets.
2684  if (N.getValueType() != MVT::i64)
2685  return false;
2686 
2687  SDLoc dl(N);
2688  int64_t Imm = 0;
2689 
2690  if (N.getOpcode() == ISD::ADD) {
2691  if (!isIntS34Immediate(N.getOperand(1), Imm))
2692  return false;
2693  Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2694  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2695  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2696  else
2697  Base = N.getOperand(0);
2698  return true;
2699  }
2700 
2701  if (N.getOpcode() == ISD::OR) {
2702  if (!isIntS34Immediate(N.getOperand(1), Imm))
2703  return false;
2704  // If this is an or of disjoint bitfields, we can codegen this as an add
2705  // (for better address arithmetic) if the LHS and RHS of the OR are
2706  // provably disjoint.
2707  KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2708  if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2709  return false;
2710  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2711  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2712  else
2713  Base = N.getOperand(0);
2714  Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2715  return true;
2716  }
2717 
2718  if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2719  Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2720  Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2721  return true;
2722  }
2723 
2724  return false;
2725 }
2726 
2727 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2728 /// represented as an indexed [r+r] operation.
2730  SDValue &Index,
2731  SelectionDAG &DAG) const {
2732  // Check to see if we can easily represent this as an [r+r] address. This
2733  // will fail if it thinks that the address is more profitably represented as
2734  // reg+imm, e.g. where imm = 0.
2735  if (SelectAddressRegReg(N, Base, Index, DAG))
2736  return true;
2737 
2738  // If the address is the result of an add, we will utilize the fact that the
2739  // address calculation includes an implicit add. However, we can reduce
2740  // register pressure if we do not materialize a constant just for use as the
2741  // index register. We only get rid of the add if it is not an add of a
2742  // value and a 16-bit signed constant and both have a single use.
2743  int16_t imm = 0;
2744  if (N.getOpcode() == ISD::ADD &&
2745  (!isIntS16Immediate(N.getOperand(1), imm) ||
2746  !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2747  Base = N.getOperand(0);
2748  Index = N.getOperand(1);
2749  return true;
2750  }
2751 
2752  // Otherwise, do it the hard way, using R0 as the base register.
2753  Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2754  N.getValueType());
2755  Index = N;
2756  return true;
2757 }
2758 
2759 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2760  Ty *PCRelCand = dyn_cast<Ty>(N);
2761  return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2762 }
2763 
2764 /// Returns true if this address is a PC Relative address.
2765 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2766 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2768  // This is a materialize PC Relative node. Always select this as PC Relative.
2769  Base = N;
2770  if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2771  return true;
2772  if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2773  isValidPCRelNode<GlobalAddressSDNode>(N) ||
2774  isValidPCRelNode<JumpTableSDNode>(N) ||
2775  isValidPCRelNode<BlockAddressSDNode>(N))
2776  return true;
2777  return false;
2778 }
2779 
2780 /// Returns true if we should use a direct load into vector instruction
2781 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2783 
2784  // If there are any other uses other than scalar to vector, then we should
2785  // keep it as a scalar load -> direct move pattern to prevent multiple
2786  // loads.
2787  LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2788  if (!LD)
2789  return false;
2790 
2791  EVT MemVT = LD->getMemoryVT();
2792  if (!MemVT.isSimple())
2793  return false;
2794  switch(MemVT.getSimpleVT().SimpleTy) {
2795  case MVT::i64:
2796  break;
2797  case MVT::i32:
2798  if (!ST.hasP8Vector())
2799  return false;
2800  break;
2801  case MVT::i16:
2802  case MVT::i8:
2803  if (!ST.hasP9Vector())
2804  return false;
2805  break;
2806  default:
2807  return false;
2808  }
2809 
2810  SDValue LoadedVal(N, 0);
2811  if (!LoadedVal.hasOneUse())
2812  return false;
2813 
2814  for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2815  UI != UE; ++UI)
2816  if (UI.getUse().get().getResNo() == 0 &&
2817  UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2818  UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2819  return false;
2820 
2821  return true;
2822 }
2823 
2824 /// getPreIndexedAddressParts - returns true by value, base pointer and
2825 /// offset pointer and addressing mode by reference if the node's address
2826 /// can be legally represented as pre-indexed load / store address.
2828  SDValue &Offset,
2829  ISD::MemIndexedMode &AM,
2830  SelectionDAG &DAG) const {
2831  if (DisablePPCPreinc) return false;
2832 
2833  bool isLoad = true;
2834  SDValue Ptr;
2835  EVT VT;
2836  unsigned Alignment;
2837  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2838  Ptr = LD->getBasePtr();
2839  VT = LD->getMemoryVT();
2840  Alignment = LD->getAlignment();
2841  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2842  Ptr = ST->getBasePtr();
2843  VT = ST->getMemoryVT();
2844  Alignment = ST->getAlignment();
2845  isLoad = false;
2846  } else
2847  return false;
2848 
2849  // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2850  // instructions because we can fold these into a more efficient instruction
2851  // instead, (such as LXSD).
2852  if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2853  return false;
2854  }
2855 
2856  // PowerPC doesn't have preinc load/store instructions for vectors
2857  if (VT.isVector())
2858  return false;
2859 
2860  if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2861  // Common code will reject creating a pre-inc form if the base pointer
2862  // is a frame index, or if N is a store and the base pointer is either
2863  // the same as or a predecessor of the value being stored. Check for
2864  // those situations here, and try with swapped Base/Offset instead.
2865  bool Swap = false;
2866 
2867  if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2868  Swap = true;
2869  else if (!isLoad) {
2870  SDValue Val = cast<StoreSDNode>(N)->getValue();
2871  if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2872  Swap = true;
2873  }
2874 
2875  if (Swap)
2876  std::swap(Base, Offset);
2877 
2878  AM = ISD::PRE_INC;
2879  return true;
2880  }
2881 
2882  // LDU/STU can only handle immediates that are a multiple of 4.
2883  if (VT != MVT::i64) {
2884  if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
2885  return false;
2886  } else {
2887  // LDU/STU need an address with at least 4-byte alignment.
2888  if (Alignment < 4)
2889  return false;
2890 
2891  if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
2892  return false;
2893  }
2894 
2895  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2896  // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
2897  // sext i32 to i64 when addr mode is r+i.
2898  if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2899  LD->getExtensionType() == ISD::SEXTLOAD &&
2900  isa<ConstantSDNode>(Offset))
2901  return false;
2902  }
2903 
2904  AM = ISD::PRE_INC;
2905  return true;
2906 }
2907 
2908 //===----------------------------------------------------------------------===//
2909 // LowerOperation implementation
2910 //===----------------------------------------------------------------------===//
2911 
2912 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2913 /// and LoOpFlags to the target MO flags.
2914 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2915  unsigned &HiOpFlags, unsigned &LoOpFlags,
2916  const GlobalValue *GV = nullptr) {
2917  HiOpFlags = PPCII::MO_HA;
2918  LoOpFlags = PPCII::MO_LO;
2919 
2920  // Don't use the pic base if not in PIC relocation model.
2921  if (IsPIC) {
2922  HiOpFlags |= PPCII::MO_PIC_FLAG;
2923  LoOpFlags |= PPCII::MO_PIC_FLAG;
2924  }
2925 }
2926 
2927 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2928  SelectionDAG &DAG) {
2929  SDLoc DL(HiPart);
2930  EVT PtrVT = HiPart.getValueType();
2931  SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2932 
2933  SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2934  SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2935 
2936  // With PIC, the first instruction is actually "GR+hi(&G)".
2937  if (isPIC)
2938  Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2939  DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2940 
2941  // Generate non-pic code that has direct accesses to the constant pool.
2942  // The address of the global is just (hi(&g)+lo(&g)).
2943  return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2944 }
2945 
2947  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2948  FuncInfo->setUsesTOCBasePtr();
2949 }
2950 
2951 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2953 }
2954 
2955 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2956  SDValue GA) const {
2957  const bool Is64Bit = Subtarget.isPPC64();
2958  EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2959  SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2960  : Subtarget.isAIXABI()
2961  ? DAG.getRegister(PPC::R2, VT)
2962  : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2963  SDValue Ops[] = { GA, Reg };
2964  return DAG.getMemIntrinsicNode(
2965  PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2968 }
2969 
2970 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2971  SelectionDAG &DAG) const {
2972  EVT PtrVT = Op.getValueType();
2973  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2974  const Constant *C = CP->getConstVal();
2975 
2976  // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2977  // The actual address of the GlobalValue is stored in the TOC.
2978  if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2979  if (Subtarget.isUsingPCRelativeCalls()) {
2980  SDLoc DL(CP);
2981  EVT Ty = getPointerTy(DAG.getDataLayout());
2982  SDValue ConstPool = DAG.getTargetConstantPool(
2983  C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
2984  return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2985  }
2986  setUsesTOCBasePtr(DAG);
2987  SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
2988  return getTOCEntry(DAG, SDLoc(CP), GA);
2989  }
2990 
2991  unsigned MOHiFlag, MOLoFlag;
2992  bool IsPIC = isPositionIndependent();
2993  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2994 
2995  if (IsPIC && Subtarget.isSVR4ABI()) {
2996  SDValue GA =
2997  DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
2998  return getTOCEntry(DAG, SDLoc(CP), GA);
2999  }
3000 
3001  SDValue CPIHi =
3002  DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
3003  SDValue CPILo =
3004  DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
3005  return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
3006 }
3007 
3008 // For 64-bit PowerPC, prefer the more compact relative encodings.
3009 // This trades 32 bits per jump table entry for one or two instructions
3010 // on the jump site.
3012  if (isJumpTableRelative())
3014 
3016 }
3017 
3020  return false;
3021  if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3022  return true;
3024 }
3025 
3027  SelectionDAG &DAG) const {
3028  if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3029  return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3030 
3031  switch (getTargetMachine().getCodeModel()) {
3032  case CodeModel::Small:
3033  case CodeModel::Medium:
3034  return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3035  default:
3036  return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3037  getPointerTy(DAG.getDataLayout()));
3038  }
3039 }
3040 
3041 const MCExpr *
3043  unsigned JTI,
3044  MCContext &Ctx) const {
3045  if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3046  return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3047 
3048  switch (getTargetMachine().getCodeModel()) {
3049  case CodeModel::Small:
3050  case CodeModel::Medium:
3051  return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3052  default:
3053  return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3054  }
3055 }
3056 
3057 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3058  EVT PtrVT = Op.getValueType();
3059  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3060 
3061  // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3062  if (Subtarget.isUsingPCRelativeCalls()) {
3063  SDLoc DL(JT);
3064  EVT Ty = getPointerTy(DAG.getDataLayout());
3065  SDValue GA =
3066  DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
3067  SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3068  return MatAddr;
3069  }
3070 
3071  // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3072  // The actual address of the GlobalValue is stored in the TOC.
3073  if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3074  setUsesTOCBasePtr(DAG);
3075  SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3076  return getTOCEntry(DAG, SDLoc(JT), GA);
3077  }
3078 
3079  unsigned MOHiFlag, MOLoFlag;
3080  bool IsPIC = isPositionIndependent();
3081  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3082 
3083  if (IsPIC && Subtarget.isSVR4ABI()) {
3084  SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3086  return getTOCEntry(DAG, SDLoc(GA), GA);
3087  }
3088 
3089  SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3090  SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3091  return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3092 }
3093 
3094 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3095  SelectionDAG &DAG) const {
3096  EVT PtrVT = Op.getValueType();
3097  BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3098  const BlockAddress *BA = BASDN->getBlockAddress();
3099 
3100  // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3101  if (Subtarget.isUsingPCRelativeCalls()) {
3102  SDLoc DL(BASDN);
3103  EVT Ty = getPointerTy(DAG.getDataLayout());
3104  SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3106  SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3107  return MatAddr;
3108  }
3109 
3110  // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3111  // The actual BlockAddress is stored in the TOC.
3112  if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3113  setUsesTOCBasePtr(DAG);
3114  SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3115  return getTOCEntry(DAG, SDLoc(BASDN), GA);
3116  }
3117 
3118  // 32-bit position-independent ELF stores the BlockAddress in the .got.
3119  if (Subtarget.is32BitELFABI() && isPositionIndependent())
3120  return getTOCEntry(
3121  DAG, SDLoc(BASDN),
3122  DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3123 
3124  unsigned MOHiFlag, MOLoFlag;
3125  bool IsPIC = isPositionIndependent();
3126  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3127  SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3128  SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3129  return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3130 }
3131 
3132 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3133  SelectionDAG &DAG) const {
3134  if (Subtarget.isAIXABI())
3135  return LowerGlobalTLSAddressAIX(Op, DAG);
3136 
3137  return LowerGlobalTLSAddressLinux(Op, DAG);
3138 }
3139 
3140 SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
3141  SelectionDAG &DAG) const {
3142  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3143 
3144  if (DAG.getTarget().useEmulatedTLS())
3145  report_fatal_error("Emulated TLS is not yet supported on AIX");
3146 
3147  SDLoc dl(GA);
3148  const GlobalValue *GV = GA->getGlobal();
3149  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3150 
3151  // The general-dynamic model is the only access model supported for now, so
3152  // all the GlobalTLSAddress nodes are lowered with this model.
3153  // We need to generate two TOC entries, one for the variable offset, one for
3154  // the region handle. The global address for the TOC entry of the region
3155  // handle is created with the MO_TLSGD_FLAG flag so we can easily identify
3156  // this entry and add the right relocation.
3157  SDValue VariableOffsetTGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3158  SDValue RegionHandleTGA =
3159  DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG);
3160  SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3161  SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA);
3162  return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset,
3163  RegionHandle);
3164 }
3165 
3166 SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op,
3167  SelectionDAG &DAG) const {
3168  // FIXME: TLS addresses currently use medium model code sequences,
3169  // which is the most useful form. Eventually support for small and
3170  // large models could be added if users need it, at the cost of
3171  // additional complexity.
3172  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3173  if (DAG.getTarget().useEmulatedTLS())
3174  return LowerToTLSEmulatedModel(GA, DAG);
3175 
3176  SDLoc dl(GA);
3177  const GlobalValue *GV = GA->getGlobal();
3178  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3179  bool is64bit = Subtarget.isPPC64();
3180  const Module *M = DAG.getMachineFunction().getFunction().getParent();
3181  PICLevel::Level picLevel = M->getPICLevel();
3182 
3183  const TargetMachine &TM = getTargetMachine();
3184  TLSModel::Model Model = TM.getTLSModel(GV);
3185 
3186  if (Model == TLSModel::LocalExec) {
3187  if (Subtarget.isUsingPCRelativeCalls()) {
3188  SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3189  SDValue TGA = DAG.getTargetGlobalAddress(
3190  GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
3191  SDValue MatAddr =
3192  DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3193  return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3194  }
3195 
3196  SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3198  SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3200  SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3201  : DAG.getRegister(PPC::R2, MVT::i32);
3202 
3203  SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3204  return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3205  }
3206 
3207  if (Model == TLSModel::InitialExec) {
3208  bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3209  SDValue TGA = DAG.getTargetGlobalAddress(
3210  GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3211  SDValue TGATLS = DAG.getTargetGlobalAddress(
3212  GV, dl, PtrVT, 0,
3214  SDValue TPOffset;
3215  if (IsPCRel) {
3216  SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3217  TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3218  MachinePointerInfo());
3219  } else {
3220  SDValue GOTPtr;
3221  if (is64bit) {
3222  setUsesTOCBasePtr(DAG);
3223  SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3224  GOTPtr =
3225  DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3226  } else {
3227  if (!TM.isPositionIndependent())
3228  GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3229  else if (picLevel == PICLevel::SmallPIC)
3230  GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3231  else
3232  GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3233  }
3234  TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3235  }
3236  return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3237  }
3238 
3240  if (Subtarget.isUsingPCRelativeCalls()) {
3241  SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3243  return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3244  }
3245 
3246  SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3247  SDValue GOTPtr;
3248  if (is64bit) {
3249  setUsesTOCBasePtr(DAG);
3250  SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3251  GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3252  GOTReg, TGA);
3253  } else {
3254  if (picLevel == PICLevel::SmallPIC)
3255  GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3256  else
3257  GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3258  }
3259  return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3260  GOTPtr, TGA, TGA);
3261  }
3262 
3263  if (Model == TLSModel::LocalDynamic) {
3264  if (Subtarget.isUsingPCRelativeCalls()) {
3265  SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3267  SDValue MatPCRel =
3268  DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3269  return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3270  }
3271 
3272  SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3273  SDValue GOTPtr;
3274  if (is64bit) {
3275  setUsesTOCBasePtr(DAG);
3276  SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3277  GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3278  GOTReg, TGA);
3279  } else {
3280  if (picLevel == PICLevel::SmallPIC)
3281  GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3282  else
3283  GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3284  }
3285  SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3286  PtrVT, GOTPtr, TGA, TGA);
3287  SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3288  PtrVT, TLSAddr, TGA);
3289  return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3290  }
3291 
3292  llvm_unreachable("Unknown TLS model!");
3293 }
3294 
3295 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3296  SelectionDAG &DAG) const {
3297  EVT PtrVT = Op.getValueType();
3298  GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3299  SDLoc DL(GSDN);
3300  const GlobalValue *GV = GSDN->getGlobal();
3301 
3302  // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3303  // The actual address of the GlobalValue is stored in the TOC.
3304  if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3305  if (Subtarget.isUsingPCRelativeCalls()) {
3306  EVT Ty = getPointerTy(DAG.getDataLayout());
3307  if (isAccessedAsGotIndirect(Op)) {
3308  SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3311  SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3312  SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3313  MachinePointerInfo());
3314  return Load;
3315  } else {
3316  SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3318  return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3319  }
3320  }
3321  setUsesTOCBasePtr(DAG);
3322  SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3323  return getTOCEntry(DAG, DL, GA);
3324  }
3325 
3326  unsigned MOHiFlag, MOLoFlag;
3327  bool IsPIC = isPositionIndependent();
3328  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3329 
3330  if (IsPIC && Subtarget.isSVR4ABI()) {
3331  SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3332  GSDN->getOffset(),
3334  return getTOCEntry(DAG, DL, GA);
3335  }
3336 
3337  SDValue GAHi =
3338  DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3339  SDValue GALo =
3340  DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3341 
3342  return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3343 }
3344 
3345 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3346  bool IsStrict = Op->isStrictFPOpcode();
3347  ISD::CondCode CC =
3348  cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
3349  SDValue LHS = Op.getOperand(IsStrict ? 1 : 0);
3350  SDValue RHS = Op.getOperand(IsStrict ? 2 : 1);
3351  SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
3352  EVT LHSVT = LHS.getValueType();
3353  SDLoc dl(Op);
3354 
3355  // Soften the setcc with libcall if it is fp128.
3356  if (LHSVT == MVT::f128) {
3357  assert(!Subtarget.hasP9Vector() &&
3358  "SETCC for f128 is already legal under Power9!");
3359  softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain,
3360  Op->getOpcode() == ISD::STRICT_FSETCCS);
3361  if (RHS.getNode())
3362  LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS,
3363  DAG.getCondCode(CC));
3364  if (IsStrict)
3365  return DAG.getMergeValues({LHS, Chain}, dl);
3366  return LHS;
3367  }
3368 
3369  assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!");
3370 
3371  if (Op.getValueType() == MVT::v2i64) {
3372  // When the operands themselves are v2i64 values, we need to do something
3373  // special because VSX has no underlying comparison operations for these.
3374  if (LHS.getValueType() == MVT::v2i64) {
3375  // Equality can be handled by casting to the legal type for Altivec
3376  // comparisons, everything else needs to be expanded.
3377  if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3378  return DAG.getNode(
3379  ISD::BITCAST, dl, MVT::v2i64,
3380  DAG.getSetCC(dl, MVT::v4i32,
3381  DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS),
3382  DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC));
3383  }
3384 
3385  return SDValue();
3386  }
3387 
3388  // We handle most of these in the usual way.
3389  return Op;
3390  }
3391 
3392  // If we're comparing for equality to zero, expose the fact that this is
3393  // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3394  // fold the new nodes.
3395  if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3396  return V;
3397 
3398  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
3399  // Leave comparisons against 0 and -1 alone for now, since they're usually
3400  // optimized. FIXME: revisit this when we can custom lower all setcc
3401  // optimizations.
3402  if (C->isAllOnesValue() || C->isNullValue())
3403  return SDValue();
3404  }
3405 
3406  // If we have an integer seteq/setne, turn it into a compare against zero
3407  // by xor'ing the rhs with the lhs, which is faster than setting a
3408  // condition register, reading it back out, and masking the correct bit. The
3409  // normal approach here uses sub to do this instead of xor. Using xor exposes
3410  // the result to other bit-twiddling opportunities.
3411  if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3412  EVT VT = Op.getValueType();
3413  SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS);
3414  return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3415  }
3416  return SDValue();
3417 }
3418 
3419 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3420  SDNode *Node = Op.getNode();
3421  EVT VT = Node->getValueType(0);
3422  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3423  SDValue InChain = Node->getOperand(0);
3424  SDValue VAListPtr = Node->getOperand(1);
3425  const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3426  SDLoc dl(Node);
3427 
3428  assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3429 
3430  // gpr_index
3431  SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3432  VAListPtr, MachinePointerInfo(SV), MVT::i8);
3433  InChain = GprIndex.getValue(1);
3434 
3435  if (VT == MVT::i64) {
3436  // Check if GprIndex is even
3437  SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3438  DAG.getConstant(1, dl, MVT::i32));
3439  SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3440  DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3441  SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3442  DAG.getConstant(1, dl, MVT::i32));
3443  // Align GprIndex to be even if it isn't
3444  GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3445  GprIndex);
3446  }
3447 
3448  // fpr index is 1 byte after gpr
3449  SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3450  DAG.getConstant(1, dl, MVT::i32));
3451 
3452  // fpr
3453  SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3454  FprPtr, MachinePointerInfo(SV), MVT::i8);
3455  InChain = FprIndex.getValue(1);
3456 
3457  SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3458  DAG.getConstant(8, dl, MVT::i32));
3459 
3460  SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3461  DAG.getConstant(4, dl, MVT::i32));
3462 
3463  // areas
3464  SDValue OverflowArea =
3465  DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3466  InChain = OverflowArea.getValue(1);
3467 
3468  SDValue RegSaveArea =
3469  DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3470  InChain = RegSaveArea.getValue(1);
3471 
3472  // select overflow_area if index > 8
3473  SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3474  DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3475 
3476  // adjustment constant gpr_index * 4/8
3477  SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3478  VT.isInteger() ? GprIndex : FprIndex,
3479  DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3480  MVT::i32));
3481 
3482  // OurReg = RegSaveArea + RegConstant
3483  SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3484  RegConstant);
3485 
3486  // Floating types are 32 bytes into RegSaveArea
3487  if (VT.isFloatingPoint())
3488  OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3489  DAG.getConstant(32, dl, MVT::i32));
3490 
3491  // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3492  SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3493  VT.isInteger() ? GprIndex : FprIndex,
3494  DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3495  MVT::i32));
3496 
3497  InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3498  VT.isInteger() ? VAListPtr : FprPtr,
3500 
3501  // determine if we should load from reg_save_area or overflow_area
3502  SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3503 
3504  // increase overflow_area by 4/8 if gpr/fpr > 8
3505  SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3506  DAG.getConstant(VT.isInteger() ? 4 : 8,
3507  dl, MVT::i32));
3508 
3509  OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3510  OverflowAreaPlusN);
3511 
3512  InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3514 
3515  return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3516 }
3517 
3518 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3519  assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3520 
3521  // We have to copy the entire va_list struct:
3522  // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3523  return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3524  DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3525  false, true, false, MachinePointerInfo(),
3526  MachinePointerInfo());
3527 }
3528 
3529 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3530  SelectionDAG &DAG) const {
3531  if (Subtarget.isAIXABI())
3532  report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3533 
3534  return Op.getOperand(0);
3535 }
3536 
3537 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3538  SelectionDAG &DAG) const {
3539  if (Subtarget.isAIXABI())
3540  report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3541 
3542  SDValue Chain = Op.getOperand(