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