LLVM  14.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 
125  "ppc-quadword-atomics",
126  cl::desc("enable quadword lock-free atomic operations"), cl::init(false),
127  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 static const char AIXSSPCanaryWordName[] = "__ssp_canary_word";
139 
140 // FIXME: Remove this once the bug has been fixed!
142 
144  const PPCSubtarget &STI)
145  : TargetLowering(TM), Subtarget(STI) {
146  // Initialize map that relates the PPC addressing modes to the computed flags
147  // of a load/store instruction. The map is used to determine the optimal
148  // addressing mode when selecting load and stores.
149  initializeAddrModeMap();
150  // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
151  // arguments are at least 4/8 bytes aligned.
152  bool isPPC64 = Subtarget.isPPC64();
153  setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
154 
155  // Set up the register classes.
156  addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
157  if (!useSoftFloat()) {
158  if (hasSPE()) {
159  addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
160  // EFPU2 APU only supports f32
161  if (!Subtarget.hasEFPU2())
162  addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
163  } else {
164  addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
165  addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
166  }
167  }
168 
169  // Match BITREVERSE to customized fast code sequence in the td file.
172 
173  // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
175 
176  // Custom lower inline assembly to check for special registers.
179 
180  // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
181  for (MVT VT : MVT::integer_valuetypes()) {
184  }
185 
186  if (Subtarget.isISA3_0()) {
191  } else {
192  // No extending loads from f16 or HW conversions back and forth.
201  }
202 
204 
205  // PowerPC has pre-inc load and store's.
216  if (!Subtarget.hasSPE()) {
221  }
222 
223  // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
224  const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
225  for (MVT VT : ScalarIntVTs) {
230  }
231 
232  if (Subtarget.useCRBits()) {
234 
235  if (isPPC64 || Subtarget.hasFPCVT()) {
238  isPPC64 ? MVT::i64 : MVT::i32);
241  isPPC64 ? MVT::i64 : MVT::i32);
242 
245  isPPC64 ? MVT::i64 : MVT::i32);
248  isPPC64 ? MVT::i64 : MVT::i32);
249 
252  isPPC64 ? MVT::i64 : MVT::i32);
255  isPPC64 ? MVT::i64 : MVT::i32);
256 
259  isPPC64 ? MVT::i64 : MVT::i32);
262  isPPC64 ? MVT::i64 : MVT::i32);
263  } else {
268  }
269 
270  // PowerPC does not support direct load/store of condition registers.
273 
274  // FIXME: Remove this once the ANDI glue bug is fixed:
275  if (ANDIGlueBug)
277 
278  for (MVT VT : MVT::integer_valuetypes()) {
282  }
283 
284  addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
285  }
286 
287  // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
288  // PPC (the libcall is not available).
293 
294  // We do not currently implement these libm ops for PowerPC.
301 
302  // PowerPC has no SREM/UREM instructions unless we are on P9
303  // On P9 we may use a hardware instruction to compute the remainder.
304  // When the result of both the remainder and the division is required it is
305  // more efficient to compute the remainder from the result of the division
306  // rather than use the remainder instruction. The instructions are legalized
307  // directly because the DivRemPairsPass performs the transformation at the IR
308  // level.
309  if (Subtarget.isISA3_0()) {
314  } else {
319  }
320 
321  // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
330 
331  // Handle constrained floating-point operations of scalar.
332  // TODO: Handle SPE specific operation.
338 
343 
344  if (!Subtarget.hasSPE()) {
347  }
348 
349  if (Subtarget.hasVSX()) {
352  }
353 
354  if (Subtarget.hasFSQRT()) {
357  }
358 
359  if (Subtarget.hasFPRND()) {
364 
369  }
370 
371  // We don't support sin/cos/sqrt/fmod/pow
382  if (Subtarget.hasSPE()) {
385  } else {
388  }
389 
390  if (Subtarget.hasSPE())
392 
394 
395  // If we're enabling GP optimizations, use hardware square root
396  if (!Subtarget.hasFSQRT() &&
397  !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
398  Subtarget.hasFRE()))
400 
401  if (!Subtarget.hasFSQRT() &&
402  !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
403  Subtarget.hasFRES()))
405 
406  if (Subtarget.hasFCPSGN()) {
409  } else {
412  }
413 
414  if (Subtarget.hasFPRND()) {
419 
424  }
425 
426  // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
427  // to speed up scalar BSWAP64.
428  // CTPOP or CTTZ were introduced in P8/P9 respectively
430  if (Subtarget.hasP9Vector() && Subtarget.isPPC64())
432  else
434  if (Subtarget.isISA3_0()) {
437  } else {
440  }
441 
442  if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
445  } else {
448  }
449 
450  // PowerPC does not have ROTR
453 
454  if (!Subtarget.useCRBits()) {
455  // PowerPC does not have Select
460  }
461 
462  // PowerPC wants to turn select_cc of FP into fsel when possible.
465 
466  // PowerPC wants to optimize integer setcc a bit
467  if (!Subtarget.useCRBits())
469 
470  if (Subtarget.hasFPU()) {
474 
478  }
479 
480  // PowerPC does not have BRCOND which requires SetCC
481  if (!Subtarget.useCRBits())
483 
485 
486  if (Subtarget.hasSPE()) {
487  // SPE has built-in conversions
494 
495  // SPE supports signaling compare of f32/f64.
498  } else {
499  // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
502 
503  // PowerPC does not have [U|S]INT_TO_FP
508  }
509 
510  if (Subtarget.hasDirectMove() && isPPC64) {
515  if (TM.Options.UnsafeFPMath) {
524  }
525  } else {
530  }
531 
532  // We cannot sextinreg(i1). Expand to shifts.
534 
535  // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
536  // SjLj exception handling but a light-weight setjmp/longjmp replacement to
537  // support continuation, user-level threading, and etc.. As a result, no
538  // other SjLj exception interfaces are implemented and please don't build
539  // your own exception handling based on them.
540  // LLVM/Clang supports zero-cost DWARF exception handling.
543 
544  // We want to legalize GlobalAddress and ConstantPool nodes into the
545  // appropriate instructions to materialize the address.
556 
557  // TRAP is legal.
559 
560  // TRAMPOLINE is custom lowered.
563 
564  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
566 
567  if (Subtarget.is64BitELFABI()) {
568  // VAARG always uses double-word chunks, so promote anything smaller.
578  } else if (Subtarget.is32BitELFABI()) {
579  // VAARG is custom lowered with the 32-bit SVR4 ABI.
582  } else
584 
585  // VACOPY is custom lowered with the 32-bit SVR4 ABI.
586  if (Subtarget.is32BitELFABI())
588  else
590 
591  // Use the default implementation.
601 
602  // We want to custom lower some of our intrinsics.
606 
607  // To handle counter-based loop conditions.
609 
614 
615  // Comparisons that require checking two conditions.
616  if (Subtarget.hasSPE()) {
621  }
634 
637 
638  if (Subtarget.has64BitSupport()) {
639  // They also have instructions for converting between i64 and fp.
648  // This is just the low 32 bits of a (signed) fp->i64 conversion.
649  // We cannot do this with Promote because i64 is not a legal type.
652 
653  if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
656  }
657  } else {
658  // PowerPC does not have FP_TO_UINT on 32-bit implementations.
659  if (Subtarget.hasSPE()) {
662  } else {
665  }
666  }
667 
668  // With the instructions enabled under FPCVT, we can do everything.
669  if (Subtarget.hasFPCVT()) {
670  if (Subtarget.has64BitSupport()) {
679  }
680 
689  }
690 
691  if (Subtarget.use64BitRegs()) {
692  // 64-bit PowerPC implementations can support i64 types directly
693  addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
694  // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
696  // 64-bit PowerPC wants to expand i128 shifts itself.
700  } else {
701  // 32-bit PowerPC wants to expand i64 shifts itself.
705  }
706 
707  // PowerPC has better expansions for funnel shifts than the generic
708  // TargetLowering::expandFunnelShift.
709  if (Subtarget.has64BitSupport()) {
712  }
715 
716  if (Subtarget.hasVSX()) {
721  }
722 
723  if (Subtarget.hasAltivec()) {
724  for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
729  }
730  // First set operation action for all vector types to expand. Then we
731  // will selectively turn on ones that can be effectively codegen'd.
732  for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
733  // add/sub are legal for all supported vector VT's.
736 
737  // For v2i64, these are only valid with P8Vector. This is corrected after
738  // the loop.
739  if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
744  }
745  else {
750  }
751 
752  if (Subtarget.hasVSX()) {
755  }
756 
757  // Vector instructions introduced in P8
758  if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
761  }
762  else {
765  }
766 
767  // Vector instructions introduced in P9
768  if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
770  else
772 
773  // We promote all shuffles to v16i8.
776 
777  // We promote all non-typed operations to v4i32.
793 
794  // No other operations are legal.
832 
833  for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
834  setTruncStoreAction(VT, InnerVT, Expand);
835  setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
836  setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
837  setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
838  }
839  }
841  if (!Subtarget.hasP8Vector()) {
846  }
847 
848  // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
849  // with merges, splats, etc.
851 
852  // Vector truncates to sub-word integer that fit in an Altivec/VSX register
853  // are cheap, so handle them before they get expanded to scalar.
859 
865  Subtarget.useCRBits() ? Legal : Expand);
879 
880  // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
882  // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
883  if (Subtarget.hasAltivec())
884  for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
886  // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
887  if (Subtarget.hasP8Altivec())
889 
890  addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
891  addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
892  addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
893  addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
894 
897 
898  if (Subtarget.hasVSX()) {
902  }
903 
904  if (Subtarget.hasP8Altivec())
906  else
908 
909  if (Subtarget.isISA3_1()) {
928  }
929 
932 
935 
940 
941  // Altivec does not contain unordered floating-point compare instructions
946 
947  if (Subtarget.hasVSX()) {
950  if (Subtarget.hasP8Vector()) {
953  }
954  if (Subtarget.hasDirectMove() && isPPC64) {
963  }
965 
966  // The nearbyint variants are not allowed to raise the inexact exception
967  // so we can only code-gen them with unsafe math.
968  if (TM.Options.UnsafeFPMath) {
971  }
972 
981 
987 
990 
993 
994  // Share the Altivec comparison restrictions.
999 
1002 
1004 
1005  if (Subtarget.hasP8Vector())
1006  addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
1007 
1008  addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
1009 
1010  addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
1011  addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
1012  addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
1013 
1014  if (Subtarget.hasP8Altivec()) {
1018 
1019  // 128 bit shifts can be accomplished via 3 instructions for SHL and
1020  // SRL, but not for SRA because of the instructions available:
1021  // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
1022  // doing
1026 
1028  }
1029  else {
1033 
1035 
1036  // VSX v2i64 only supports non-arithmetic operations.
1039  }
1040 
1041  if (Subtarget.isISA3_1())
1043  else
1045 
1050 
1052 
1061 
1062  // Custom handling for partial vectors of integers converted to
1063  // floating point. We already have optimal handling for v2i32 through
1064  // the DAG combine, so those aren't necessary.
1081 
1088 
1091 
1092  // Handle constrained floating-point operations of vector.
1093  // The predictor is `hasVSX` because altivec instruction has
1094  // no exception but VSX vector instruction has.
1108 
1122 
1123  addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1124  addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1125 
1126  for (MVT FPT : MVT::fp_valuetypes())
1128 
1129  // Expand the SELECT to SELECT_CC
1131 
1134 
1135  // No implementation for these ops for PowerPC.
1141  }
1142 
1143  if (Subtarget.hasP8Altivec()) {
1144  addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1145  addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1146  }
1147 
1148  if (Subtarget.hasP9Vector()) {
1151 
1152  // 128 bit shifts can be accomplished via 3 instructions for SHL and
1153  // SRL, but not for SRA because of the instructions available:
1154  // VS{RL} and VS{RL}O.
1158 
1164 
1172 
1179 
1183 
1184  // Handle constrained floating-point operations of fp128
1205  } else if (Subtarget.hasVSX()) {
1208 
1211 
1212  // Set FADD/FSUB as libcall to avoid the legalizer to expand the
1213  // fp_to_uint and int_to_fp.
1216 
1224 
1225  // Expand the fp_extend if the target type is fp128.
1228 
1229  // Expand the fp_round if the source type is fp128.
1230  for (MVT VT : {MVT::f32, MVT::f64}) {
1233  }
1234 
1239 
1240  // Lower following f128 select_cc pattern:
1241  // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE
1243 
1244  // We need to handle f128 SELECT_CC with integer result type.
1247  }
1248 
1249  if (Subtarget.hasP9Altivec()) {
1250  if (Subtarget.isISA3_1()) {
1256  } else {
1259  }
1267  }
1268  }
1269 
1270  if (Subtarget.pairedVectorMemops()) {
1271  addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1274  }
1275  if (Subtarget.hasMMA()) {
1276  addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1280  }
1281 
1282  if (Subtarget.has64BitSupport())
1284 
1285  if (Subtarget.isISA3_1())
1287 
1289 
1290  if (!isPPC64) {
1293  }
1294 
1295  if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics()) {
1300  }
1301 
1303 
1304  if (Subtarget.hasAltivec()) {
1305  // Altivec instructions set fields to all zeros or all ones.
1307  }
1308 
1309  if (!isPPC64) {
1310  // These libcalls are not available in 32-bit.
1311  setLibcallName(RTLIB::SHL_I128, nullptr);
1312  setLibcallName(RTLIB::SRL_I128, nullptr);
1313  setLibcallName(RTLIB::SRA_I128, nullptr);
1314  setLibcallName(RTLIB::MULO_I64, nullptr);
1315  }
1316 
1317  if (!isPPC64)
1319 
1320  setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1321 
1322  // We have target-specific dag combine patterns for the following nodes:
1331  if (Subtarget.hasFPCVT())
1336  if (Subtarget.useCRBits())
1342 
1346 
1349 
1350 
1351  if (Subtarget.useCRBits()) {
1355  }
1356 
1357  if (Subtarget.hasP9Altivec()) {
1360  }
1361 
1362  setLibcallName(RTLIB::LOG_F128, "logf128");
1363  setLibcallName(RTLIB::LOG2_F128, "log2f128");
1364  setLibcallName(RTLIB::LOG10_F128, "log10f128");
1365  setLibcallName(RTLIB::EXP_F128, "expf128");
1366  setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1367  setLibcallName(RTLIB::SIN_F128, "sinf128");
1368  setLibcallName(RTLIB::COS_F128, "cosf128");
1369  setLibcallName(RTLIB::POW_F128, "powf128");
1370  setLibcallName(RTLIB::FMIN_F128, "fminf128");
1371  setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1372  setLibcallName(RTLIB::REM_F128, "fmodf128");
1373  setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
1374  setLibcallName(RTLIB::CEIL_F128, "ceilf128");
1375  setLibcallName(RTLIB::FLOOR_F128, "floorf128");
1376  setLibcallName(RTLIB::TRUNC_F128, "truncf128");
1377  setLibcallName(RTLIB::ROUND_F128, "roundf128");
1378  setLibcallName(RTLIB::LROUND_F128, "lroundf128");
1379  setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
1380  setLibcallName(RTLIB::RINT_F128, "rintf128");
1381  setLibcallName(RTLIB::LRINT_F128, "lrintf128");
1382  setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
1383  setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
1384  setLibcallName(RTLIB::FMA_F128, "fmaf128");
1385 
1386  // With 32 condition bits, we don't need to sink (and duplicate) compares
1387  // aggressively in CodeGenPrep.
1388  if (Subtarget.useCRBits()) {
1391  }
1392 
1394 
1395  switch (Subtarget.getCPUDirective()) {
1396  default: break;
1397  case PPC::DIR_970:
1398  case PPC::DIR_A2:
1399  case PPC::DIR_E500:
1400  case PPC::DIR_E500mc:
1401  case PPC::DIR_E5500:
1402  case PPC::DIR_PWR4:
1403  case PPC::DIR_PWR5:
1404  case PPC::DIR_PWR5X:
1405  case PPC::DIR_PWR6:
1406  case PPC::DIR_PWR6X:
1407  case PPC::DIR_PWR7:
1408  case PPC::DIR_PWR8:
1409  case PPC::DIR_PWR9:
1410  case PPC::DIR_PWR10:
1411  case PPC::DIR_PWR_FUTURE:
1414  break;
1415  }
1416 
1417  if (Subtarget.enableMachineScheduler())
1419  else
1421 
1423 
1424  // The Freescale cores do better with aggressive inlining of memcpy and
1425  // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1426  if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1427  Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1428  MaxStoresPerMemset = 32;
1430  MaxStoresPerMemcpy = 32;
1432  MaxStoresPerMemmove = 32;
1434  } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1435  // The A2 also benefits from (very) aggressive inlining of memcpy and
1436  // friends. The overhead of a the function call, even when warm, can be
1437  // over one hundred cycles.
1438  MaxStoresPerMemset = 128;
1439  MaxStoresPerMemcpy = 128;
1440  MaxStoresPerMemmove = 128;
1441  MaxLoadsPerMemcmp = 128;
1442  } else {
1443  MaxLoadsPerMemcmp = 8;
1445  }
1446 
1447  IsStrictFPEnabled = true;
1448 
1449  // Let the subtarget (CPU) decide if a predictable select is more expensive
1450  // than the corresponding branch. This information is used in CGP to decide
1451  // when to convert selects into branches.
1453 }
1454 
1455 // *********************************** NOTE ************************************
1456 // For selecting load and store instructions, the addressing modes are defined
1457 // as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD
1458 // patterns to match the load the store instructions.
1459 //
1460 // The TD definitions for the addressing modes correspond to their respective
1461 // Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely
1462 // on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the
1463 // address mode flags of a particular node. Afterwards, the computed address
1464 // flags are passed into getAddrModeForFlags() in order to retrieve the optimal
1465 // addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement
1466 // accordingly, based on the preferred addressing mode.
1467 //
1468 // Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode.
1469 // MemOpFlags contains all the possible flags that can be used to compute the
1470 // optimal addressing mode for load and store instructions.
1471 // AddrMode contains all the possible load and store addressing modes available
1472 // on Power (such as DForm, DSForm, DQForm, XForm, etc.)
1473 //
1474 // When adding new load and store instructions, it is possible that new address
1475 // flags may need to be added into MemOpFlags, and a new addressing mode will
1476 // need to be added to AddrMode. An entry of the new addressing mode (consisting
1477 // of the minimal and main distinguishing address flags for the new load/store
1478 // instructions) will need to be added into initializeAddrModeMap() below.
1479 // Finally, when adding new addressing modes, the getAddrModeForFlags() will
1480 // need to be updated to account for selecting the optimal addressing mode.
1481 // *****************************************************************************
1482 /// Initialize the map that relates the different addressing modes of the load
1483 /// and store instructions to a set of flags. This ensures the load/store
1484 /// instruction is correctly matched during instruction selection.
1485 void PPCTargetLowering::initializeAddrModeMap() {
1486  AddrModesMap[PPC::AM_DForm] = {
1487  // LWZ, STW
1492  // LBZ, LHZ, STB, STH
1497  // LHA
1502  // LFS, LFD, STFS, STFD
1507  };
1508  AddrModesMap[PPC::AM_DSForm] = {
1509  // LWA
1513  // LD, STD
1517  // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64
1521  };
1522  AddrModesMap[PPC::AM_DQForm] = {
1523  // LXV, STXV
1527  };
1528  AddrModesMap[PPC::AM_PrefixDForm] = {PPC::MOF_RPlusSImm34 |
1530  // TODO: Add mapping for quadword load/store.
1531 }
1532 
1533 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1534 /// the desired ByVal argument alignment.
1535 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1536  if (MaxAlign == MaxMaxAlign)
1537  return;
1538  if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1539  if (MaxMaxAlign >= 32 &&
1540  VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1541  MaxAlign = Align(32);
1542  else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1543  MaxAlign < 16)
1544  MaxAlign = Align(16);
1545  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1546  Align EltAlign;
1547  getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1548  if (EltAlign > MaxAlign)
1549  MaxAlign = EltAlign;
1550  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1551  for (auto *EltTy : STy->elements()) {
1552  Align EltAlign;
1553  getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1554  if (EltAlign > MaxAlign)
1555  MaxAlign = EltAlign;
1556  if (MaxAlign == MaxMaxAlign)
1557  break;
1558  }
1559  }
1560 }
1561 
1562 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1563 /// function arguments in the caller parameter area.
1565  const DataLayout &DL) const {
1566  // 16byte and wider vectors are passed on 16byte boundary.
1567  // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1568  Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1569  if (Subtarget.hasAltivec())
1570  getMaxByValAlign(Ty, Alignment, Align(16));
1571  return Alignment.value();
1572 }
1573 
1575  return Subtarget.useSoftFloat();
1576 }
1577 
1579  return Subtarget.hasSPE();
1580 }
1581 
1583  return VT.isScalarInteger();
1584 }
1585 
1586 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1587  switch ((PPCISD::NodeType)Opcode) {
1588  case PPCISD::FIRST_NUMBER: break;
1589  case PPCISD::FSEL: return "PPCISD::FSEL";
1590  case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP";
1591  case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP";
1592  case PPCISD::FCFID: return "PPCISD::FCFID";
1593  case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
1594  case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
1595  case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
1596  case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
1597  case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
1598  case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
1599  case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
1601  return "PPCISD::FP_TO_UINT_IN_VSR,";
1603  return "PPCISD::FP_TO_SINT_IN_VSR";
1604  case PPCISD::FRE: return "PPCISD::FRE";
1605  case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
1606  case PPCISD::FTSQRT:
1607  return "PPCISD::FTSQRT";
1608  case PPCISD::FSQRT:
1609  return "PPCISD::FSQRT";
1610  case PPCISD::STFIWX: return "PPCISD::STFIWX";
1611  case PPCISD::VPERM: return "PPCISD::VPERM";
1612  case PPCISD::XXSPLT: return "PPCISD::XXSPLT";
1614  return "PPCISD::XXSPLTI_SP_TO_DP";
1615  case PPCISD::XXSPLTI32DX:
1616  return "PPCISD::XXSPLTI32DX";
1617  case PPCISD::VECINSERT: return "PPCISD::VECINSERT";
1618  case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI";
1619  case PPCISD::VECSHL: return "PPCISD::VECSHL";
1620  case PPCISD::CMPB: return "PPCISD::CMPB";
1621  case PPCISD::Hi: return "PPCISD::Hi";
1622  case PPCISD::Lo: return "PPCISD::Lo";
1623  case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
1624  case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1625  case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1626  case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
1627  case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET";
1628  case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA";
1629  case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
1630  case PPCISD::SRL: return "PPCISD::SRL";
1631  case PPCISD::SRA: return "PPCISD::SRA";
1632  case PPCISD::SHL: return "PPCISD::SHL";
1633  case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE";
1634  case PPCISD::CALL: return "PPCISD::CALL";
1635  case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
1636  case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC";
1637  case PPCISD::CALL_RM:
1638  return "PPCISD::CALL_RM";
1639  case PPCISD::CALL_NOP_RM:
1640  return "PPCISD::CALL_NOP_RM";
1641  case PPCISD::CALL_NOTOC_RM:
1642  return "PPCISD::CALL_NOTOC_RM";
1643  case PPCISD::MTCTR: return "PPCISD::MTCTR";
1644  case PPCISD::BCTRL: return "PPCISD::BCTRL";
1645  case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
1646  case PPCISD::BCTRL_RM:
1647  return "PPCISD::BCTRL_RM";
1649  return "PPCISD::BCTRL_LOAD_TOC_RM";
1650  case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
1651  case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
1652  case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
1653  case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1654  case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
1655  case PPCISD::MFVSR: return "PPCISD::MFVSR";
1656  case PPCISD::MTVSRA: return "PPCISD::MTVSRA";
1657  case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ";
1658  case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP";
1659  case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP";
1661  return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1663  return "PPCISD::ANDI_rec_1_EQ_BIT";
1665  return "PPCISD::ANDI_rec_1_GT_BIT";
1666  case PPCISD::VCMP: return "PPCISD::VCMP";
1667  case PPCISD::VCMP_rec: return "PPCISD::VCMP_rec";
1668  case PPCISD::LBRX: return "PPCISD::LBRX";
1669  case PPCISD::STBRX: return "PPCISD::STBRX";
1670  case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
1671  case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
1672  case PPCISD::LXSIZX: return "PPCISD::LXSIZX";
1673  case PPCISD::STXSIX: return "PPCISD::STXSIX";
1674  case PPCISD::VEXTS: return "PPCISD::VEXTS";
1675  case PPCISD::LXVD2X: return "PPCISD::LXVD2X";
1676  case PPCISD::STXVD2X: return "PPCISD::STXVD2X";
1677  case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE";
1678  case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE";
1680  return "PPCISD::ST_VSR_SCAL_INT";
1681  case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
1682  case PPCISD::BDNZ: return "PPCISD::BDNZ";
1683  case PPCISD::BDZ: return "PPCISD::BDZ";
1684  case PPCISD::MFFS: return "PPCISD::MFFS";
1685  case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
1686  case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
1687  case PPCISD::CR6SET: return "PPCISD::CR6SET";
1688  case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
1689  case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
1690  case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT";
1691  case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1692  case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
1693  case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
1694  case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
1695  case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
1696  case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
1697  case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1698  case PPCISD::TLSGD_AIX: return "PPCISD::TLSGD_AIX";
1699  case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
1700  case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
1701  case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
1702  case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1703  case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1704  case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
1705  case PPCISD::PADDI_DTPREL:
1706  return "PPCISD::PADDI_DTPREL";
1707  case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
1708  case PPCISD::SC: return "PPCISD::SC";
1709  case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB";
1710  case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE";
1711  case PPCISD::RFEBB: return "PPCISD::RFEBB";
1712  case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD";
1713  case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN";
1714  case PPCISD::VABSD: return "PPCISD::VABSD";
1715  case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128";
1716  case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64";
1717  case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE";
1718  case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI";
1719  case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH";
1720  case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF";
1721  case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR";
1723  return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1725  return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1726  case PPCISD::ACC_BUILD: return "PPCISD::ACC_BUILD";
1727  case PPCISD::PAIR_BUILD: return "PPCISD::PAIR_BUILD";
1728  case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1729  case PPCISD::XXMFACC: return "PPCISD::XXMFACC";
1730  case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT";
1731  case PPCISD::ZEXT_LD_SPLAT: return "PPCISD::ZEXT_LD_SPLAT";
1732  case PPCISD::SEXT_LD_SPLAT: return "PPCISD::SEXT_LD_SPLAT";
1733  case PPCISD::FNMSUB: return "PPCISD::FNMSUB";
1735  return "PPCISD::STRICT_FADDRTZ";
1736  case PPCISD::STRICT_FCTIDZ:
1737  return "PPCISD::STRICT_FCTIDZ";
1738  case PPCISD::STRICT_FCTIWZ:
1739  return "PPCISD::STRICT_FCTIWZ";
1741  return "PPCISD::STRICT_FCTIDUZ";
1743  return "PPCISD::STRICT_FCTIWUZ";
1744  case PPCISD::STRICT_FCFID:
1745  return "PPCISD::STRICT_FCFID";
1746  case PPCISD::STRICT_FCFIDU:
1747  return "PPCISD::STRICT_FCFIDU";
1748  case PPCISD::STRICT_FCFIDS:
1749  return "PPCISD::STRICT_FCFIDS";
1751  return "PPCISD::STRICT_FCFIDUS";
1752  case PPCISD::LXVRZX: return "PPCISD::LXVRZX";
1753  }
1754  return nullptr;
1755 }
1756 
1758  EVT VT) const {
1759  if (!VT.isVector())
1760  return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1761 
1763 }
1764 
1766  assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1767  return true;
1768 }
1769 
1770 //===----------------------------------------------------------------------===//
1771 // Node matching predicates, for use by the tblgen matching code.
1772 //===----------------------------------------------------------------------===//
1773 
1774 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1776  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1777  return CFP->getValueAPF().isZero();
1778  else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1779  // Maybe this has already been legalized into the constant pool?
1780  if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1781  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1782  return CFP->getValueAPF().isZero();
1783  }
1784  return false;
1785 }
1786 
1787 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1788 /// true if Op is undef or if it matches the specified value.
1789 static bool isConstantOrUndef(int Op, int Val) {
1790  return Op < 0 || Op == Val;
1791 }
1792 
1793 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1794 /// VPKUHUM instruction.
1795 /// The ShuffleKind distinguishes between big-endian operations with
1796 /// two different inputs (0), either-endian operations with two identical
1797 /// inputs (1), and little-endian operations with two different inputs (2).
1798 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1800  SelectionDAG &DAG) {
1801  bool IsLE = DAG.getDataLayout().isLittleEndian();
1802  if (ShuffleKind == 0) {
1803  if (IsLE)
1804  return false;
1805  for (unsigned i = 0; i != 16; ++i)
1806  if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1807  return false;
1808  } else if (ShuffleKind == 2) {
1809  if (!IsLE)
1810  return false;
1811  for (unsigned i = 0; i != 16; ++i)
1812  if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1813  return false;
1814  } else if (ShuffleKind == 1) {
1815  unsigned j = IsLE ? 0 : 1;
1816  for (unsigned i = 0; i != 8; ++i)
1817  if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1818  !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1819  return false;
1820  }
1821  return true;
1822 }
1823 
1824 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1825 /// VPKUWUM instruction.
1826 /// The ShuffleKind distinguishes between big-endian operations with
1827 /// two different inputs (0), either-endian operations with two identical
1828 /// inputs (1), and little-endian operations with two different inputs (2).
1829 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1831  SelectionDAG &DAG) {
1832  bool IsLE = DAG.getDataLayout().isLittleEndian();
1833  if (ShuffleKind == 0) {
1834  if (IsLE)
1835  return false;
1836  for (unsigned i = 0; i != 16; i += 2)
1837  if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1838  !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1839  return false;
1840  } else if (ShuffleKind == 2) {
1841  if (!IsLE)
1842  return false;
1843  for (unsigned i = 0; i != 16; i += 2)
1844  if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1845  !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1846  return false;
1847  } else if (ShuffleKind == 1) {
1848  unsigned j = IsLE ? 0 : 2;
1849  for (unsigned i = 0; i != 8; i += 2)
1850  if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1851  !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1852  !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1853  !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1854  return false;
1855  }
1856  return true;
1857 }
1858 
1859 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1860 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1861 /// current subtarget.
1862 ///
1863 /// The ShuffleKind distinguishes between big-endian operations with
1864 /// two different inputs (0), either-endian operations with two identical
1865 /// inputs (1), and little-endian operations with two different inputs (2).
1866 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1868  SelectionDAG &DAG) {
1869  const PPCSubtarget& Subtarget =
1870  static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1871  if (!Subtarget.hasP8Vector())
1872  return false;
1873 
1874  bool IsLE = DAG.getDataLayout().isLittleEndian();
1875  if (ShuffleKind == 0) {
1876  if (IsLE)
1877  return false;
1878  for (unsigned i = 0; i != 16; i += 4)
1879  if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) ||
1880  !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) ||
1881  !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) ||
1882  !isConstantOrUndef(N->getMaskElt(i+3), i*2+7))
1883  return false;
1884  } else if (ShuffleKind == 2) {
1885  if (!IsLE)
1886  return false;
1887  for (unsigned i = 0; i != 16; i += 4)
1888  if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1889  !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) ||
1890  !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) ||
1891  !isConstantOrUndef(N->getMaskElt(i+3), i*2+3))
1892  return false;
1893  } else if (ShuffleKind == 1) {
1894  unsigned j = IsLE ? 0 : 4;
1895  for (unsigned i = 0; i != 8; i += 4)
1896  if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1897  !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1898  !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) ||
1899  !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) ||
1900  !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1901  !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) ||
1902  !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1903  !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1904  return false;
1905  }
1906  return true;
1907 }
1908 
1909 /// isVMerge - Common function, used to match vmrg* shuffles.
1910 ///
1911 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1912  unsigned LHSStart, unsigned RHSStart) {
1913  if (N->getValueType(0) != MVT::v16i8)
1914  return false;
1915  assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1916  "Unsupported merge size!");
1917 
1918  for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
1919  for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
1920  if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1921  LHSStart+j+i*UnitSize) ||
1922  !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1923  RHSStart+j+i*UnitSize))
1924  return false;
1925  }
1926  return true;
1927 }
1928 
1929 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1930 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1931 /// The ShuffleKind distinguishes between big-endian merges with two
1932 /// different inputs (0), either-endian merges with two identical inputs (1),
1933 /// and little-endian merges with two different inputs (2). For the latter,
1934 /// the input operands are swapped (see PPCInstrAltivec.td).
1936  unsigned ShuffleKind, SelectionDAG &DAG) {
1937  if (DAG.getDataLayout().isLittleEndian()) {
1938  if (ShuffleKind == 1) // unary
1939  return isVMerge(N, UnitSize, 0, 0);
1940  else if (ShuffleKind == 2) // swapped
1941  return isVMerge(N, UnitSize, 0, 16);
1942  else
1943  return false;
1944  } else {
1945  if (ShuffleKind == 1) // unary
1946  return isVMerge(N, UnitSize, 8, 8);
1947  else if (ShuffleKind == 0) // normal
1948  return isVMerge(N, UnitSize, 8, 24);
1949  else
1950  return false;
1951  }
1952 }
1953 
1954 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1955 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1956 /// The ShuffleKind distinguishes between big-endian merges with two
1957 /// different inputs (0), either-endian merges with two identical inputs (1),
1958 /// and little-endian merges with two different inputs (2). For the latter,
1959 /// the input operands are swapped (see PPCInstrAltivec.td).
1961  unsigned ShuffleKind, SelectionDAG &DAG) {
1962  if (DAG.getDataLayout().isLittleEndian()) {
1963  if (ShuffleKind == 1) // unary
1964  return isVMerge(N, UnitSize, 8, 8);
1965  else if (ShuffleKind == 2) // swapped
1966  return isVMerge(N, UnitSize, 8, 24);
1967  else
1968  return false;
1969  } else {
1970  if (ShuffleKind == 1) // unary
1971  return isVMerge(N, UnitSize, 0, 0);
1972  else if (ShuffleKind == 0) // normal
1973  return isVMerge(N, UnitSize, 0, 16);
1974  else
1975  return false;
1976  }
1977 }
1978 
1979 /**
1980  * Common function used to match vmrgew and vmrgow shuffles
1981  *
1982  * The indexOffset determines whether to look for even or odd words in
1983  * the shuffle mask. This is based on the of the endianness of the target
1984  * machine.
1985  * - Little Endian:
1986  * - Use offset of 0 to check for odd elements
1987  * - Use offset of 4 to check for even elements
1988  * - Big Endian:
1989  * - Use offset of 0 to check for even elements
1990  * - Use offset of 4 to check for odd elements
1991  * A detailed description of the vector element ordering for little endian and
1992  * big endian can be found at
1993  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1994  * Targeting your applications - what little endian and big endian IBM XL C/C++
1995  * compiler differences mean to you
1996  *
1997  * The mask to the shuffle vector instruction specifies the indices of the
1998  * elements from the two input vectors to place in the result. The elements are
1999  * numbered in array-access order, starting with the first vector. These vectors
2000  * are always of type v16i8, thus each vector will contain 16 elements of size
2001  * 8. More info on the shuffle vector can be found in the
2002  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
2003  * Language Reference.
2004  *
2005  * The RHSStartValue indicates whether the same input vectors are used (unary)
2006  * or two different input vectors are used, based on the following:
2007  * - If the instruction uses the same vector for both inputs, the range of the
2008  * indices will be 0 to 15. In this case, the RHSStart value passed should
2009  * be 0.
2010  * - If the instruction has two different vectors then the range of the
2011  * indices will be 0 to 31. In this case, the RHSStart value passed should
2012  * be 16 (indices 0-15 specify elements in the first vector while indices 16
2013  * to 31 specify elements in the second vector).
2014  *
2015  * \param[in] N The shuffle vector SD Node to analyze
2016  * \param[in] IndexOffset Specifies whether to look for even or odd elements
2017  * \param[in] RHSStartValue Specifies the starting index for the righthand input
2018  * vector to the shuffle_vector instruction
2019  * \return true iff this shuffle vector represents an even or odd word merge
2020  */
2021 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
2022  unsigned RHSStartValue) {
2023  if (N->getValueType(0) != MVT::v16i8)
2024  return false;
2025 
2026  for (unsigned i = 0; i < 2; ++i)
2027  for (unsigned j = 0; j < 4; ++j)
2028  if (!isConstantOrUndef(N->getMaskElt(i*4+j),
2029  i*RHSStartValue+j+IndexOffset) ||
2030  !isConstantOrUndef(N->getMaskElt(i*4+j+8),
2031  i*RHSStartValue+j+IndexOffset+8))
2032  return false;
2033  return true;
2034 }
2035 
2036 /**
2037  * Determine if the specified shuffle mask is suitable for the vmrgew or
2038  * vmrgow instructions.
2039  *
2040  * \param[in] N The shuffle vector SD Node to analyze
2041  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
2042  * \param[in] ShuffleKind Identify the type of merge:
2043  * - 0 = big-endian merge with two different inputs;
2044  * - 1 = either-endian merge with two identical inputs;
2045  * - 2 = little-endian merge with two different inputs (inputs are swapped for
2046  * little-endian merges).
2047  * \param[in] DAG The current SelectionDAG
2048  * \return true iff this shuffle mask
2049  */
2051  unsigned ShuffleKind, SelectionDAG &DAG) {
2052  if (DAG.getDataLayout().isLittleEndian()) {
2053  unsigned indexOffset = CheckEven ? 4 : 0;
2054  if (ShuffleKind == 1) // Unary
2055  return isVMerge(N, indexOffset, 0);
2056  else if (ShuffleKind == 2) // swapped
2057  return isVMerge(N, indexOffset, 16);
2058  else
2059  return false;
2060  }
2061  else {
2062  unsigned indexOffset = CheckEven ? 0 : 4;
2063  if (ShuffleKind == 1) // Unary
2064  return isVMerge(N, indexOffset, 0);
2065  else if (ShuffleKind == 0) // Normal
2066  return isVMerge(N, indexOffset, 16);
2067  else
2068  return false;
2069  }
2070  return false;
2071 }
2072 
2073 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
2074 /// amount, otherwise return -1.
2075 /// The ShuffleKind distinguishes between big-endian operations with two
2076 /// different inputs (0), either-endian operations with two identical inputs
2077 /// (1), and little-endian operations with two different inputs (2). For the
2078 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
2079 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
2080  SelectionDAG &DAG) {
2081  if (N->getValueType(0) != MVT::v16i8)
2082  return -1;
2083 
2084  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2085 
2086  // Find the first non-undef value in the shuffle mask.
2087  unsigned i;
2088  for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
2089  /*search*/;
2090 
2091  if (i == 16) return -1; // all undef.
2092 
2093  // Otherwise, check to see if the rest of the elements are consecutively
2094  // numbered from this value.
2095  unsigned ShiftAmt = SVOp->getMaskElt(i);
2096  if (ShiftAmt < i) return -1;
2097 
2098  ShiftAmt -= i;
2099  bool isLE = DAG.getDataLayout().isLittleEndian();
2100 
2101  if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
2102  // Check the rest of the elements to see if they are consecutive.
2103  for (++i; i != 16; ++i)
2104  if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2105  return -1;
2106  } else if (ShuffleKind == 1) {
2107  // Check the rest of the elements to see if they are consecutive.
2108  for (++i; i != 16; ++i)
2109  if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
2110  return -1;
2111  } else
2112  return -1;
2113 
2114  if (isLE)
2115  ShiftAmt = 16 - ShiftAmt;
2116 
2117  return ShiftAmt;
2118 }
2119 
2120 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
2121 /// specifies a splat of a single element that is suitable for input to
2122 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
2124  assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
2125  EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
2126 
2127  // The consecutive indices need to specify an element, not part of two
2128  // different elements. So abandon ship early if this isn't the case.
2129  if (N->getMaskElt(0) % EltSize != 0)
2130  return false;
2131 
2132  // This is a splat operation if each element of the permute is the same, and
2133  // if the value doesn't reference the second vector.
2134  unsigned ElementBase = N->getMaskElt(0);
2135 
2136  // FIXME: Handle UNDEF elements too!
2137  if (ElementBase >= 16)
2138  return false;
2139 
2140  // Check that the indices are consecutive, in the case of a multi-byte element
2141  // splatted with a v16i8 mask.
2142  for (unsigned i = 1; i != EltSize; ++i)
2143  if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2144  return false;
2145 
2146  for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2147  if (N->getMaskElt(i) < 0) continue;
2148  for (unsigned j = 0; j != EltSize; ++j)
2149  if (N->getMaskElt(i+j) != N->getMaskElt(j))
2150  return false;
2151  }
2152  return true;
2153 }
2154 
2155 /// Check that the mask is shuffling N byte elements. Within each N byte
2156 /// element of the mask, the indices could be either in increasing or
2157 /// decreasing order as long as they are consecutive.
2158 /// \param[in] N the shuffle vector SD Node to analyze
2159 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2160 /// Word/DoubleWord/QuadWord).
2161 /// \param[in] StepLen the delta indices number among the N byte element, if
2162 /// the mask is in increasing/decreasing order then it is 1/-1.
2163 /// \return true iff the mask is shuffling N byte elements.
2165  int StepLen) {
2166  assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
2167  "Unexpected element width.");
2168  assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2169 
2170  unsigned NumOfElem = 16 / Width;
2171  unsigned MaskVal[16]; // Width is never greater than 16
2172  for (unsigned i = 0; i < NumOfElem; ++i) {
2173  MaskVal[0] = N->getMaskElt(i * Width);
2174  if ((StepLen == 1) && (MaskVal[0] % Width)) {
2175  return false;
2176  } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2177  return false;
2178  }
2179 
2180  for (unsigned int j = 1; j < Width; ++j) {
2181  MaskVal[j] = N->getMaskElt(i * Width + j);
2182  if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2183  return false;
2184  }
2185  }
2186  }
2187 
2188  return true;
2189 }
2190 
2191 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2192  unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2193  if (!isNByteElemShuffleMask(N, 4, 1))
2194  return false;
2195 
2196  // Now we look at mask elements 0,4,8,12
2197  unsigned M0 = N->getMaskElt(0) / 4;
2198  unsigned M1 = N->getMaskElt(4) / 4;
2199  unsigned M2 = N->getMaskElt(8) / 4;
2200  unsigned M3 = N->getMaskElt(12) / 4;
2201  unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2202  unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2203 
2204  // Below, let H and L be arbitrary elements of the shuffle mask
2205  // where H is in the range [4,7] and L is in the range [0,3].
2206  // H, 1, 2, 3 or L, 5, 6, 7
2207  if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2208  (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2209  ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2210  InsertAtByte = IsLE ? 12 : 0;
2211  Swap = M0 < 4;
2212  return true;
2213  }
2214  // 0, H, 2, 3 or 4, L, 6, 7
2215  if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2216  (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2217  ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2218  InsertAtByte = IsLE ? 8 : 4;
2219  Swap = M1 < 4;
2220  return true;
2221  }
2222  // 0, 1, H, 3 or 4, 5, L, 7
2223  if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2224  (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2225  ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2226  InsertAtByte = IsLE ? 4 : 8;
2227  Swap = M2 < 4;
2228  return true;
2229  }
2230  // 0, 1, 2, H or 4, 5, 6, L
2231  if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2232  (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2233  ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2234  InsertAtByte = IsLE ? 0 : 12;
2235  Swap = M3 < 4;
2236  return true;
2237  }
2238 
2239  // If both vector operands for the shuffle are the same vector, the mask will
2240  // contain only elements from the first one and the second one will be undef.
2241  if (N->getOperand(1).isUndef()) {
2242  ShiftElts = 0;
2243  Swap = true;
2244  unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2245  if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2246  InsertAtByte = IsLE ? 12 : 0;
2247  return true;
2248  }
2249  if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2250  InsertAtByte = IsLE ? 8 : 4;
2251  return true;
2252  }
2253  if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2254  InsertAtByte = IsLE ? 4 : 8;
2255  return true;
2256  }
2257  if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2258  InsertAtByte = IsLE ? 0 : 12;
2259  return true;
2260  }
2261  }
2262 
2263  return false;
2264 }
2265 
2267  bool &Swap, bool IsLE) {
2268  assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2269  // Ensure each byte index of the word is consecutive.
2270  if (!isNByteElemShuffleMask(N, 4, 1))
2271  return false;
2272 
2273  // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2274  unsigned M0 = N->getMaskElt(0) / 4;
2275  unsigned M1 = N->getMaskElt(4) / 4;
2276  unsigned M2 = N->getMaskElt(8) / 4;
2277  unsigned M3 = N->getMaskElt(12) / 4;
2278 
2279  // If both vector operands for the shuffle are the same vector, the mask will
2280  // contain only elements from the first one and the second one will be undef.
2281  if (N->getOperand(1).isUndef()) {
2282  assert(M0 < 4 && "Indexing into an undef vector?");
2283  if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2284  return false;
2285 
2286  ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2287  Swap = false;
2288  return true;
2289  }
2290 
2291  // Ensure each word index of the ShuffleVector Mask is consecutive.
2292  if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2293  return false;
2294 
2295  if (IsLE) {
2296  if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2297  // Input vectors don't need to be swapped if the leading element
2298  // of the result is one of the 3 left elements of the second vector
2299  // (or if there is no shift to be done at all).
2300  Swap = false;
2301  ShiftElts = (8 - M0) % 8;
2302  } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2303  // Input vectors need to be swapped if the leading element
2304  // of the result is one of the 3 left elements of the first vector
2305  // (or if we're shifting by 4 - thereby simply swapping the vectors).
2306  Swap = true;
2307  ShiftElts = (4 - M0) % 4;
2308  }
2309 
2310  return true;
2311  } else { // BE
2312  if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2313  // Input vectors don't need to be swapped if the leading element
2314  // of the result is one of the 4 elements of the first vector.
2315  Swap = false;
2316  ShiftElts = M0;
2317  } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2318  // Input vectors need to be swapped if the leading element
2319  // of the result is one of the 4 elements of the right vector.
2320  Swap = true;
2321  ShiftElts = M0 - 4;
2322  }
2323 
2324  return true;
2325  }
2326 }
2327 
2329  assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2330 
2331  if (!isNByteElemShuffleMask(N, Width, -1))
2332  return false;
2333 
2334  for (int i = 0; i < 16; i += Width)
2335  if (N->getMaskElt(i) != i + Width - 1)
2336  return false;
2337 
2338  return true;
2339 }
2340 
2342  return isXXBRShuffleMaskHelper(N, 2);
2343 }
2344 
2346  return isXXBRShuffleMaskHelper(N, 4);
2347 }
2348 
2350  return isXXBRShuffleMaskHelper(N, 8);
2351 }
2352 
2354  return isXXBRShuffleMaskHelper(N, 16);
2355 }
2356 
2357 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2358 /// if the inputs to the instruction should be swapped and set \p DM to the
2359 /// value for the immediate.
2360 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2361 /// AND element 0 of the result comes from the first input (LE) or second input
2362 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2363 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2364 /// mask.
2366  bool &Swap, bool IsLE) {
2367  assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2368 
2369  // Ensure each byte index of the double word is consecutive.
2370  if (!isNByteElemShuffleMask(N, 8, 1))
2371  return false;
2372 
2373  unsigned M0 = N->getMaskElt(0) / 8;
2374  unsigned M1 = N->getMaskElt(8) / 8;
2375  assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2376 
2377  // If both vector operands for the shuffle are the same vector, the mask will
2378  // contain only elements from the first one and the second one will be undef.
2379  if (N->getOperand(1).isUndef()) {
2380  if ((M0 | M1) < 2) {
2381  DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2382  Swap = false;
2383  return true;
2384  } else
2385  return false;
2386  }
2387 
2388  if (IsLE) {
2389  if (M0 > 1 && M1 < 2) {
2390  Swap = false;
2391  } else if (M0 < 2 && M1 > 1) {
2392  M0 = (M0 + 2) % 4;
2393  M1 = (M1 + 2) % 4;
2394  Swap = true;
2395  } else
2396  return false;
2397 
2398  // Note: if control flow comes here that means Swap is already set above
2399  DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2400  return true;
2401  } else { // BE
2402  if (M0 < 2 && M1 > 1) {
2403  Swap = false;
2404  } else if (M0 > 1 && M1 < 2) {
2405  M0 = (M0 + 2) % 4;
2406  M1 = (M1 + 2) % 4;
2407  Swap = true;
2408  } else
2409  return false;
2410 
2411  // Note: if control flow comes here that means Swap is already set above
2412  DM = (M0 << 1) + (M1 & 1);
2413  return true;
2414  }
2415 }
2416 
2417 
2418 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2419 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2420 /// elements are counted from the left of the vector register).
2421 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2422  SelectionDAG &DAG) {
2423  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2424  assert(isSplatShuffleMask(SVOp, EltSize));
2425  if (DAG.getDataLayout().isLittleEndian())
2426  return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2427  else
2428  return SVOp->getMaskElt(0) / EltSize;
2429 }
2430 
2431 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2432 /// by using a vspltis[bhw] instruction of the specified element size, return
2433 /// the constant being splatted. The ByteSize field indicates the number of
2434 /// bytes of each element [124] -> [bhw].
2435 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2436  SDValue OpVal(nullptr, 0);
2437 
2438  // If ByteSize of the splat is bigger than the element size of the
2439  // build_vector, then we have a case where we are checking for a splat where
2440  // multiple elements of the buildvector are folded together into a single
2441  // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2442  unsigned EltSize = 16/N->getNumOperands();
2443  if (EltSize < ByteSize) {
2444  unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
2445  SDValue UniquedVals[4];
2446  assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2447 
2448  // See if all of the elements in the buildvector agree across.
2449  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2450  if (N->getOperand(i).isUndef()) continue;
2451  // If the element isn't a constant, bail fully out.
2452  if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2453 
2454  if (!UniquedVals[i&(Multiple-1)].getNode())
2455  UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2456  else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2457  return SDValue(); // no match.
2458  }
2459 
2460  // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2461  // either constant or undef values that are identical for each chunk. See
2462  // if these chunks can form into a larger vspltis*.
2463 
2464  // Check to see if all of the leading entries are either 0 or -1. If
2465  // neither, then this won't fit into the immediate field.
2466  bool LeadingZero = true;
2467  bool LeadingOnes = true;
2468  for (unsigned i = 0; i != Multiple-1; ++i) {
2469  if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
2470 
2471  LeadingZero &= isNullConstant(UniquedVals[i]);
2472  LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2473  }
2474  // Finally, check the least significant entry.
2475  if (LeadingZero) {
2476  if (!UniquedVals[Multiple-1].getNode())
2477  return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
2478  int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2479  if (Val < 16) // 0,0,0,4 -> vspltisw(4)
2480  return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2481  }
2482  if (LeadingOnes) {
2483  if (!UniquedVals[Multiple-1].getNode())
2484  return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2485  int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2486  if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
2487  return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2488  }
2489 
2490  return SDValue();
2491  }
2492 
2493  // Check to see if this buildvec has a single non-undef value in its elements.
2494  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2495  if (N->getOperand(i).isUndef()) continue;
2496  if (!OpVal.getNode())
2497  OpVal = N->getOperand(i);
2498  else if (OpVal != N->getOperand(i))
2499  return SDValue();
2500  }
2501 
2502  if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
2503 
2504  unsigned ValSizeInBytes = EltSize;
2505  uint64_t Value = 0;
2506  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2507  Value = CN->getZExtValue();
2508  } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2509  assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2510  Value = FloatToBits(CN->getValueAPF().convertToFloat());
2511  }
2512 
2513  // If the splat value is larger than the element value, then we can never do
2514  // this splat. The only case that we could fit the replicated bits into our
2515  // immediate field for would be zero, and we prefer to use vxor for it.
2516  if (ValSizeInBytes < ByteSize) return SDValue();
2517 
2518  // If the element value is larger than the splat value, check if it consists
2519  // of a repeated bit pattern of size ByteSize.
2520  if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2521  return SDValue();
2522 
2523  // Properly sign extend the value.
2524  int MaskVal = SignExtend32(Value, ByteSize * 8);
2525 
2526  // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2527  if (MaskVal == 0) return SDValue();
2528 
2529  // Finally, if this value fits in a 5 bit sext field, return it
2530  if (SignExtend32<5>(MaskVal) == MaskVal)
2531  return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2532  return SDValue();
2533 }
2534 
2535 //===----------------------------------------------------------------------===//
2536 // Addressing Mode Selection
2537 //===----------------------------------------------------------------------===//
2538 
2539 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2540 /// or 64-bit immediate, and if the value can be accurately represented as a
2541 /// sign extension from a 16-bit value. If so, this returns true and the
2542 /// immediate.
2543 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2544  if (!isa<ConstantSDNode>(N))
2545  return false;
2546 
2547  Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2548  if (N->getValueType(0) == MVT::i32)
2549  return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2550  else
2551  return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2552 }
2553 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2554  return isIntS16Immediate(Op.getNode(), Imm);
2555 }
2556 
2557 /// Used when computing address flags for selecting loads and stores.
2558 /// If we have an OR, check if the LHS and RHS are provably disjoint.
2559 /// An OR of two provably disjoint values is equivalent to an ADD.
2560 /// Most PPC load/store instructions compute the effective address as a sum,
2561 /// so doing this conversion is useful.
2562 static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) {
2563  if (N.getOpcode() != ISD::OR)
2564  return false;
2565  KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2566  if (!LHSKnown.Zero.getBoolValue())
2567  return false;
2568  KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2569  return (~(LHSKnown.Zero | RHSKnown.Zero) == 0);
2570 }
2571 
2572 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2573 /// be represented as an indexed [r+r] operation.
2575  SDValue &Index,
2576  SelectionDAG &DAG) const {
2577  for (SDNode *U : N->uses()) {
2578  if (MemSDNode *Memop = dyn_cast<MemSDNode>(U)) {
2579  if (Memop->getMemoryVT() == MVT::f64) {
2580  Base = N.getOperand(0);
2581  Index = N.getOperand(1);
2582  return true;
2583  }
2584  }
2585  }
2586  return false;
2587 }
2588 
2589 /// isIntS34Immediate - This method tests if value of node given can be
2590 /// accurately represented as a sign extension from a 34-bit value. If so,
2591 /// this returns true and the immediate.
2592 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2593  if (!isa<ConstantSDNode>(N))
2594  return false;
2595 
2596  Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2597  return isInt<34>(Imm);
2598 }
2599 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) {
2600  return isIntS34Immediate(Op.getNode(), Imm);
2601 }
2602 
2603 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2604 /// can be represented as an indexed [r+r] operation. Returns false if it
2605 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2606 /// non-zero and N can be represented by a base register plus a signed 16-bit
2607 /// displacement, make a more precise judgement by checking (displacement % \p
2608 /// EncodingAlignment).
2611  MaybeAlign EncodingAlignment) const {
2612  // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2613  // a [pc+imm].
2614  if (SelectAddressPCRel(N, Base))
2615  return false;
2616 
2617  int16_t Imm = 0;
2618  if (N.getOpcode() == ISD::ADD) {
2619  // Is there any SPE load/store (f64), which can't handle 16bit offset?
2620  // SPE load/store can only handle 8-bit offsets.
2621  if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2622  return true;
2623  if (isIntS16Immediate(N.getOperand(1), Imm) &&
2624  (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2625  return false; // r+i
2626  if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2627  return false; // r+i
2628 
2629  Base = N.getOperand(0);
2630  Index = N.getOperand(1);
2631  return true;
2632  } else if (N.getOpcode() == ISD::OR) {
2633  if (isIntS16Immediate(N.getOperand(1), Imm) &&
2634  (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2635  return false; // r+i can fold it if we can.
2636 
2637  // If this is an or of disjoint bitfields, we can codegen this as an add
2638  // (for better address arithmetic) if the LHS and RHS of the OR are provably
2639  // disjoint.
2640  KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2641 
2642  if (LHSKnown.Zero.getBoolValue()) {
2643  KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2644  // If all of the bits are known zero on the LHS or RHS, the add won't
2645  // carry.
2646  if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2647  Base = N.getOperand(0);
2648  Index = N.getOperand(1);
2649  return true;
2650  }
2651  }
2652  }
2653 
2654  return false;
2655 }
2656 
2657 // If we happen to be doing an i64 load or store into a stack slot that has
2658 // less than a 4-byte alignment, then the frame-index elimination may need to
2659 // use an indexed load or store instruction (because the offset may not be a
2660 // multiple of 4). The extra register needed to hold the offset comes from the
2661 // register scavenger, and it is possible that the scavenger will need to use
2662 // an emergency spill slot. As a result, we need to make sure that a spill slot
2663 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2664 // stack slot.
2665 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2666  // FIXME: This does not handle the LWA case.
2667  if (VT != MVT::i64)
2668  return;
2669 
2670  // NOTE: We'll exclude negative FIs here, which come from argument
2671  // lowering, because there are no known test cases triggering this problem
2672  // using packed structures (or similar). We can remove this exclusion if
2673  // we find such a test case. The reason why this is so test-case driven is
2674  // because this entire 'fixup' is only to prevent crashes (from the
2675  // register scavenger) on not-really-valid inputs. For example, if we have:
2676  // %a = alloca i1
2677  // %b = bitcast i1* %a to i64*
2678  // store i64* a, i64 b
2679  // then the store should really be marked as 'align 1', but is not. If it
2680  // were marked as 'align 1' then the indexed form would have been
2681  // instruction-selected initially, and the problem this 'fixup' is preventing
2682  // won't happen regardless.
2683  if (FrameIdx < 0)
2684  return;
2685 
2686  MachineFunction &MF = DAG.getMachineFunction();
2687  MachineFrameInfo &MFI = MF.getFrameInfo();
2688 
2689  if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2690  return;
2691 
2692  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2693  FuncInfo->setHasNonRISpills();
2694 }
2695 
2696 /// Returns true if the address N can be represented by a base register plus
2697 /// a signed 16-bit displacement [r+imm], and if it is not better
2698 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept
2699 /// displacements that are multiples of that value.
2701  SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2702  MaybeAlign EncodingAlignment) const {
2703  // FIXME dl should come from parent load or store, not from address
2704  SDLoc dl(N);
2705 
2706  // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2707  // a [pc+imm].
2708  if (SelectAddressPCRel(N, Base))
2709  return false;
2710 
2711  // If this can be more profitably realized as r+r, fail.
2712  if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2713  return false;
2714 
2715  if (N.getOpcode() == ISD::ADD) {
2716  int16_t imm = 0;
2717  if (isIntS16Immediate(N.getOperand(1), imm) &&
2718  (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2719  Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2720  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2721  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2722  fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2723  } else {
2724  Base = N.getOperand(0);
2725  }
2726  return true; // [r+i]
2727  } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2728  // Match LOAD (ADD (X, Lo(G))).
2729  assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2730  && "Cannot handle constant offsets yet!");
2731  Disp = N.getOperand(1).getOperand(0); // The global address.
2734  Disp.getOpcode() == ISD::TargetConstantPool ||
2735  Disp.getOpcode() == ISD::TargetJumpTable);
2736  Base = N.getOperand(0);
2737  return true; // [&g+r]
2738  }
2739  } else if (N.getOpcode() == ISD::OR) {
2740  int16_t imm = 0;
2741  if (isIntS16Immediate(N.getOperand(1), imm) &&
2742  (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2743  // If this is an or of disjoint bitfields, we can codegen this as an add
2744  // (for better address arithmetic) if the LHS and RHS of the OR are
2745  // provably disjoint.
2746  KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2747 
2748  if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2749  // If all of the bits are known zero on the LHS or RHS, the add won't
2750  // carry.
2751  if (FrameIndexSDNode *FI =
2752  dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2753  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2754  fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2755  } else {
2756  Base = N.getOperand(0);
2757  }
2758  Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2759  return true;
2760  }
2761  }
2762  } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2763  // Loading from a constant address.
2764 
2765  // If this address fits entirely in a 16-bit sext immediate field, codegen
2766  // this as "d, 0"
2767  int16_t Imm;
2768  if (isIntS16Immediate(CN, Imm) &&
2769  (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2770  Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2771  Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2772  CN->getValueType(0));
2773  return true;
2774  }
2775 
2776  // Handle 32-bit sext immediates with LIS + addr mode.
2777  if ((CN->getValueType(0) == MVT::i32 ||
2778  (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2779  (!EncodingAlignment ||
2780  isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2781  int Addr = (int)CN->getZExtValue();
2782 
2783  // Otherwise, break this down into an LIS + disp.
2784  Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2785 
2786  Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2787  MVT::i32);
2788  unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2789  Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2790  return true;
2791  }
2792  }
2793 
2794  Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2795  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2796  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2797  fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2798  } else
2799  Base = N;
2800  return true; // [r+0]
2801 }
2802 
2803 /// Similar to the 16-bit case but for instructions that take a 34-bit
2804 /// displacement field (prefixed loads/stores).
2806  SDValue &Base,
2807  SelectionDAG &DAG) const {
2808  // Only on 64-bit targets.
2809  if (N.getValueType() != MVT::i64)
2810  return false;
2811 
2812  SDLoc dl(N);
2813  int64_t Imm = 0;
2814 
2815  if (N.getOpcode() == ISD::ADD) {
2816  if (!isIntS34Immediate(N.getOperand(1), Imm))
2817  return false;
2818  Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2819  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2820  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2821  else
2822  Base = N.getOperand(0);
2823  return true;
2824  }
2825 
2826  if (N.getOpcode() == ISD::OR) {
2827  if (!isIntS34Immediate(N.getOperand(1), Imm))
2828  return false;
2829  // If this is an or of disjoint bitfields, we can codegen this as an add
2830  // (for better address arithmetic) if the LHS and RHS of the OR are
2831  // provably disjoint.
2832  KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2833  if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2834  return false;
2835  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2836  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2837  else
2838  Base = N.getOperand(0);
2839  Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2840  return true;
2841  }
2842 
2843  if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2844  Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2845  Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2846  return true;
2847  }
2848 
2849  return false;
2850 }
2851 
2852 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2853 /// represented as an indexed [r+r] operation.
2855  SDValue &Index,
2856  SelectionDAG &DAG) const {
2857  // Check to see if we can easily represent this as an [r+r] address. This
2858  // will fail if it thinks that the address is more profitably represented as
2859  // reg+imm, e.g. where imm = 0.
2860  if (SelectAddressRegReg(N, Base, Index, DAG))
2861  return true;
2862 
2863  // If the address is the result of an add, we will utilize the fact that the
2864  // address calculation includes an implicit add. However, we can reduce
2865  // register pressure if we do not materialize a constant just for use as the
2866  // index register. We only get rid of the add if it is not an add of a
2867  // value and a 16-bit signed constant and both have a single use.
2868  int16_t imm = 0;
2869  if (N.getOpcode() == ISD::ADD &&
2870  (!isIntS16Immediate(N.getOperand(1), imm) ||
2871  !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2872  Base = N.getOperand(0);
2873  Index = N.getOperand(1);
2874  return true;
2875  }
2876 
2877  // Otherwise, do it the hard way, using R0 as the base register.
2878  Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2879  N.getValueType());
2880  Index = N;
2881  return true;
2882 }
2883 
2884 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2885  Ty *PCRelCand = dyn_cast<Ty>(N);
2886  return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2887 }
2888 
2889 /// Returns true if this address is a PC Relative address.
2890 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2891 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2893  // This is a materialize PC Relative node. Always select this as PC Relative.
2894  Base = N;
2895  if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2896  return true;
2897  if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2898  isValidPCRelNode<GlobalAddressSDNode>(N) ||
2899  isValidPCRelNode<JumpTableSDNode>(N) ||
2900  isValidPCRelNode<BlockAddressSDNode>(N))
2901  return true;
2902  return false;
2903 }
2904 
2905 /// Returns true if we should use a direct load into vector instruction
2906 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2908 
2909  // If there are any other uses other than scalar to vector, then we should
2910  // keep it as a scalar load -> direct move pattern to prevent multiple
2911  // loads.
2912  LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2913  if (!LD)
2914  return false;
2915 
2916  EVT MemVT = LD->getMemoryVT();
2917  if (!MemVT.isSimple())
2918  return false;
2919  switch(MemVT.getSimpleVT().SimpleTy) {
2920  case MVT::i64:
2921  break;
2922  case MVT::i32:
2923  if (!ST.hasP8Vector())
2924  return false;
2925  break;
2926  case MVT::i16:
2927  case MVT::i8:
2928  if (!ST.hasP9Vector())
2929  return false;
2930  break;
2931  default:
2932  return false;
2933  }
2934 
2935  SDValue LoadedVal(N, 0);
2936  if (!LoadedVal.hasOneUse())
2937  return false;
2938 
2939  for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2940  UI != UE; ++UI)
2941  if (UI.getUse().get().getResNo() == 0 &&
2942  UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2943  UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2944  return false;
2945 
2946  return true;
2947 }
2948 
2949 /// getPreIndexedAddressParts - returns true by value, base pointer and
2950 /// offset pointer and addressing mode by reference if the node's address
2951 /// can be legally represented as pre-indexed load / store address.
2953  SDValue &Offset,
2954  ISD::MemIndexedMode &AM,
2955  SelectionDAG &DAG) const {
2956  if (DisablePPCPreinc) return false;
2957 
2958  bool isLoad = true;
2959  SDValue Ptr;
2960  EVT VT;
2961  unsigned Alignment;
2962  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2963  Ptr = LD->getBasePtr();
2964  VT = LD->getMemoryVT();
2965  Alignment = LD->getAlignment();
2966  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2967  Ptr = ST->getBasePtr();
2968  VT = ST->getMemoryVT();
2969  Alignment = ST->getAlignment();
2970  isLoad = false;
2971  } else
2972  return false;
2973 
2974  // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2975  // instructions because we can fold these into a more efficient instruction
2976  // instead, (such as LXSD).
2977  if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2978  return false;
2979  }
2980 
2981  // PowerPC doesn't have preinc load/store instructions for vectors
2982  if (VT.isVector())
2983  return false;
2984 
2985  if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2986  // Common code will reject creating a pre-inc form if the base pointer
2987  // is a frame index, or if N is a store and the base pointer is either
2988  // the same as or a predecessor of the value being stored. Check for
2989  // those situations here, and try with swapped Base/Offset instead.
2990  bool Swap = false;
2991 
2992  if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2993  Swap = true;
2994  else if (!isLoad) {
2995  SDValue Val = cast<StoreSDNode>(N)->getValue();
2996  if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2997  Swap = true;
2998  }
2999 
3000  if (Swap)
3001  std::swap(Base, Offset);
3002 
3003  AM = ISD::PRE_INC;
3004  return true;
3005  }
3006 
3007  // LDU/STU can only handle immediates that are a multiple of 4.
3008  if (VT != MVT::i64) {
3009  if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
3010  return false;
3011  } else {
3012  // LDU/STU need an address with at least 4-byte alignment.
3013  if (Alignment < 4)
3014  return false;
3015 
3016  if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
3017  return false;
3018  }
3019 
3020  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3021  // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
3022  // sext i32 to i64 when addr mode is r+i.
3023  if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
3024  LD->getExtensionType() == ISD::SEXTLOAD &&
3025  isa<ConstantSDNode>(Offset))
3026  return false;
3027  }
3028 
3029  AM = ISD::PRE_INC;
3030  return true;
3031 }
3032 
3033 //===----------------------------------------------------------------------===//
3034 // LowerOperation implementation
3035 //===----------------------------------------------------------------------===//
3036 
3037 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
3038 /// and LoOpFlags to the target MO flags.
3039 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
3040  unsigned &HiOpFlags, unsigned &LoOpFlags,
3041  const GlobalValue *GV = nullptr) {
3042  HiOpFlags = PPCII::MO_HA;
3043  LoOpFlags = PPCII::MO_LO;
3044 
3045  // Don't use the pic base if not in PIC relocation model.
3046  if (IsPIC) {
3047  HiOpFlags |= PPCII::MO_PIC_FLAG;
3048  LoOpFlags |= PPCII::MO_PIC_FLAG;
3049  }
3050 }
3051 
3052 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
3053  SelectionDAG &DAG) {
3054  SDLoc DL(HiPart);
3055  EVT PtrVT = HiPart.getValueType();
3056  SDValue Zero = DAG.getConstant(0, DL, PtrVT);
3057 
3058  SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
3059  SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
3060 
3061  // With PIC, the first instruction is actually "GR+hi(&G)".
3062  if (isPIC)
3063  Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
3064  DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
3065 
3066  // Generate non-pic code that has direct accesses to the constant pool.
3067  // The address of the global is just (hi(&g)+lo(&g)).
3068  return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
3069 }
3070 
3072  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3073  FuncInfo->setUsesTOCBasePtr();
3074 }
3075 
3076 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
3078 }
3079 
3080 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
3081  SDValue GA) const {
3082  const bool Is64Bit = Subtarget.isPPC64();
3083  EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
3084  SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
3085  : Subtarget.isAIXABI()
3086  ? DAG.getRegister(PPC::R2, VT)
3087  : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
3088  SDValue Ops[] = { GA, Reg };
3089  return DAG.getMemIntrinsicNode(
3090  PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
3093 }
3094 
3095 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
3096  SelectionDAG &DAG) const {
3097  EVT PtrVT = Op.getValueType();
3098  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3099  const Constant *C = CP->getConstVal();
3100 
3101  // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3102  // The actual address of the GlobalValue is stored in the TOC.
3103  if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3104  if (Subtarget.isUsingPCRelativeCalls()) {
3105  SDLoc DL(CP);
3106  EVT Ty = getPointerTy(DAG.getDataLayout());
3107  SDValue ConstPool = DAG.getTargetConstantPool(
3108  C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
3109  return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
3110  }
3111  setUsesTOCBasePtr(DAG);
3112  SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
3113  return getTOCEntry(DAG, SDLoc(CP), GA);
3114  }
3115 
3116  unsigned MOHiFlag, MOLoFlag;
3117  bool IsPIC = isPositionIndependent();
3118  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3119 
3120  if (IsPIC && Subtarget.isSVR4ABI()) {
3121  SDValue GA =
3122  DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
3123  return getTOCEntry(DAG, SDLoc(CP), GA);
3124  }
3125 
3126  SDValue CPIHi =
3127  DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
3128  SDValue CPILo =
3129  DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
3130  return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
3131 }
3132 
3133 // For 64-bit PowerPC, prefer the more compact relative encodings.
3134 // This trades 32 bits per jump table entry for one or two instructions
3135 // on the jump site.
3137  if (isJumpTableRelative())
3139 
3141 }
3142 
3145  return false;
3146  if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3147  return true;
3149 }
3150 
3152  SelectionDAG &DAG) const {
3153  if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3154  return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3155 
3156  switch (getTargetMachine().getCodeModel()) {
3157  case CodeModel::Small:
3158  case CodeModel::Medium:
3159  return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3160  default:
3161  return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3162  getPointerTy(DAG.getDataLayout()));
3163  }
3164 }
3165 
3166 const MCExpr *
3168  unsigned JTI,
3169  MCContext &Ctx) const {
3170  if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3171  return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3172 
3173  switch (getTargetMachine().getCodeModel()) {
3174  case CodeModel::Small:
3175  case CodeModel::Medium:
3176  return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3177  default:
3178  return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3179  }
3180 }
3181 
3182 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3183  EVT PtrVT = Op.getValueType();
3184  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3185 
3186  // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3187  if (Subtarget.isUsingPCRelativeCalls()) {
3188  SDLoc DL(JT);
3189  EVT Ty = getPointerTy(DAG.getDataLayout());
3190  SDValue GA =
3191  DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
3192  SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3193  return MatAddr;
3194  }
3195 
3196  // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3197  // The actual address of the GlobalValue is stored in the TOC.
3198  if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3199  setUsesTOCBasePtr(DAG);
3200  SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3201  return getTOCEntry(DAG, SDLoc(JT), GA);
3202  }
3203 
3204  unsigned MOHiFlag, MOLoFlag;
3205  bool IsPIC = isPositionIndependent();
3206  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3207 
3208  if (IsPIC && Subtarget.isSVR4ABI()) {
3209  SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3211  return getTOCEntry(DAG, SDLoc(GA), GA);
3212  }
3213 
3214  SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3215  SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3216  return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3217 }
3218 
3219 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3220  SelectionDAG &DAG) const {
3221  EVT PtrVT = Op.getValueType();
3222  BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3223  const BlockAddress *BA = BASDN->getBlockAddress();
3224 
3225  // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3226  if (Subtarget.isUsingPCRelativeCalls()) {
3227  SDLoc DL(BASDN);
3228  EVT Ty = getPointerTy(DAG.getDataLayout());
3229  SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3231  SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3232  return MatAddr;
3233  }
3234 
3235  // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3236  // The actual BlockAddress is stored in the TOC.
3237  if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3238  setUsesTOCBasePtr(DAG);
3239  SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3240  return getTOCEntry(DAG, SDLoc(BASDN), GA);
3241  }
3242 
3243  // 32-bit position-independent ELF stores the BlockAddress in the .got.
3244  if (Subtarget.is32BitELFABI() && isPositionIndependent())
3245  return getTOCEntry(
3246  DAG, SDLoc(BASDN),
3247  DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3248 
3249  unsigned MOHiFlag, MOLoFlag;
3250  bool IsPIC = isPositionIndependent();
3251  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3252  SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3253  SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3254  return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3255 }
3256 
3257 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3258  SelectionDAG &DAG) const {
3259  if (Subtarget.isAIXABI())
3260  return LowerGlobalTLSAddressAIX(Op, DAG);
3261 
3262  return LowerGlobalTLSAddressLinux(Op, DAG);
3263 }
3264 
3265 SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
3266  SelectionDAG &DAG) const {
3267  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3268 
3269  if (DAG.getTarget().useEmulatedTLS())
3270  report_fatal_error("Emulated TLS is not yet supported on AIX");
3271 
3272  SDLoc dl(GA);
3273  const GlobalValue *GV = GA->getGlobal();
3274  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3275 
3276  // The general-dynamic model is the only access model supported for now, so
3277  // all the GlobalTLSAddress nodes are lowered with this model.
3278  // We need to generate two TOC entries, one for the variable offset, one for
3279  // the region handle. The global address for the TOC entry of the region
3280  // handle is created with the MO_TLSGDM_FLAG flag and the global address
3281  // for the TOC entry of the variable offset is created with MO_TLSGD_FLAG.
3282  SDValue VariableOffsetTGA =
3283  DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG);
3284  SDValue RegionHandleTGA =
3285  DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG);
3286  SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3287  SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA);
3288  return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset,
3289  RegionHandle);
3290 }
3291 
3292 SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op,
3293  SelectionDAG &DAG) const {
3294  // FIXME: TLS addresses currently use medium model code sequences,
3295  // which is the most useful form. Eventually support for small and
3296  // large models could be added if users need it, at the cost of
3297  // additional complexity.
3298  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3299  if (DAG.getTarget().useEmulatedTLS())
3300  return LowerToTLSEmulatedModel(GA, DAG);
3301 
3302  SDLoc dl(GA);
3303  const GlobalValue *GV = GA->getGlobal();
3304  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3305  bool is64bit = Subtarget.isPPC64();
3306  const Module *M = DAG.getMachineFunction().getFunction().getParent();
3307  PICLevel::Level picLevel = M->getPICLevel();
3308 
3309  const TargetMachine &TM = getTargetMachine();
3310  TLSModel::Model Model = TM.getTLSModel(GV);
3311 
3312  if (Model == TLSModel::LocalExec) {
3313  if (Subtarget.isUsingPCRelativeCalls()) {
3314  SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3315  SDValue TGA = DAG.getTargetGlobalAddress(
3316  GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
3317  SDValue MatAddr =
3318  DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3319  return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3320  }
3321 
3322  SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3324  SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3326  SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3327  : DAG.getRegister(PPC::R2, MVT::i32);
3328 
3329  SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3330  return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3331  }
3332 
3333  if (Model == TLSModel::InitialExec) {
3334  bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3335  SDValue TGA = DAG.getTargetGlobalAddress(
3336  GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3337  SDValue TGATLS = DAG.getTargetGlobalAddress(
3338  GV, dl, PtrVT, 0,
3340  SDValue TPOffset;
3341  if (IsPCRel) {
3342  SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3343  TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3344  MachinePointerInfo());
3345  } else {
3346  SDValue GOTPtr;
3347  if (is64bit) {
3348  setUsesTOCBasePtr(DAG);
3349  SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3350  GOTPtr =
3351  DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3352  } else {
3353  if (!TM.isPositionIndependent())
3354  GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3355  else if (picLevel == PICLevel::SmallPIC)
3356  GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3357  else
3358  GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3359  }
3360  TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3361  }
3362  return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3363  }
3364 
3366  if (Subtarget.isUsingPCRelativeCalls()) {
3367  SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3369  return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3370  }
3371 
3372  SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3373  SDValue GOTPtr;
3374  if (is64bit) {
3375  setUsesTOCBasePtr(DAG);
3376  SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3377  GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3378  GOTReg, TGA);
3379  } else {
3380  if (picLevel == PICLevel::SmallPIC)
3381  GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3382  else
3383  GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3384  }
3385  return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3386  GOTPtr, TGA, TGA);
3387  }
3388 
3389  if (Model == TLSModel::LocalDynamic) {
3390  if (Subtarget.isUsingPCRelativeCalls()) {
3391  SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3393  SDValue MatPCRel =
3394  DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3395  return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3396  }
3397 
3398  SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3399  SDValue GOTPtr;
3400  if (is64bit) {
3401  setUsesTOCBasePtr(DAG);
3402  SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3403  GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3404  GOTReg, TGA);
3405  } else {
3406  if (picLevel == PICLevel::SmallPIC)
3407  GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3408  else
3409  GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3410  }
3411  SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3412  PtrVT, GOTPtr, TGA, TGA);
3413  SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3414  PtrVT, TLSAddr, TGA);
3415  return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3416  }
3417 
3418  llvm_unreachable("Unknown TLS model!");
3419 }
3420 
3421 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3422  SelectionDAG &DAG) const {
3423  EVT PtrVT = Op.getValueType();
3424  GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3425  SDLoc DL(GSDN);
3426  const GlobalValue *GV = GSDN->getGlobal();
3427 
3428  // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3429  // The actual address of the GlobalValue is stored in the TOC.
3430  if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3431  if (Subtarget.isUsingPCRelativeCalls()) {
3432  EVT Ty = getPointerTy(DAG.getDataLayout());
3433  if (isAccessedAsGotIndirect(Op)) {
3434  SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3437  SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3438  SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3439  MachinePointerInfo());
3440  return Load;
3441  } else {
3442  SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3444  return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3445  }
3446  }
3447  setUsesTOCBasePtr(DAG);
3448  SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3449  return getTOCEntry(DAG, DL, GA);
3450  }
3451 
3452  unsigned MOHiFlag, MOLoFlag;
3453  bool IsPIC = isPositionIndependent();
3454  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3455 
3456  if (IsPIC && Subtarget.isSVR4ABI()) {
3457  SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3458  GSDN->getOffset(),
3460  return getTOCEntry(DAG, DL, GA);
3461  }
3462 
3463  SDValue GAHi =
3464  DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3465  SDValue GALo =
3466  DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3467 
3468  return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3469 }
3470 
3471 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3472  bool IsStrict = Op->isStrictFPOpcode();
3473  ISD::CondCode CC =
3474  cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
3475  SDValue LHS = Op.getOperand(IsStrict ? 1 : 0);
3476  SDValue RHS = Op.getOperand(IsStrict ? 2 : 1);
3477  SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
3478  EVT LHSVT = LHS.getValueType();
3479  SDLoc dl(Op);
3480 
3481  // Soften the setcc with libcall if it is fp128.
3482  if (LHSVT == MVT::f128) {
3483  assert(!Subtarget.hasP9Vector() &&
3484  "SETCC for f128 is already legal under Power9!");
3485  softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain,
3486  Op->getOpcode() == ISD::STRICT_FSETCCS);
3487  if (RHS.getNode())
3488  LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS,
3489  DAG.getCondCode(CC));
3490  if (IsStrict)
3491  return DAG.getMergeValues({LHS, Chain}, dl);
3492  return LHS;
3493  }
3494 
3495  assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!");
3496 
3497  if (Op.getValueType() == MVT::v2i64) {
3498  // When the operands themselves are v2i64 values, we need to do something
3499  // special because VSX has no underlying comparison operations for these.
3500  if (LHS.getValueType() == MVT::v2i64) {
3501  // Equality can be handled by casting to the legal type for Altivec
3502  // comparisons, everything else needs to be expan