LLVM 20.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"
16#include "PPC.h"
17#include "PPCCCState.h"
18#include "PPCCallingConv.h"
19#include "PPCFrameLowering.h"
20#include "PPCInstrInfo.h"
22#include "PPCPerfectShuffle.h"
23#include "PPCRegisterInfo.h"
24#include "PPCSubtarget.h"
25#include "PPCTargetMachine.h"
26#include "llvm/ADT/APFloat.h"
27#include "llvm/ADT/APInt.h"
28#include "llvm/ADT/APSInt.h"
29#include "llvm/ADT/ArrayRef.h"
30#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/SmallSet.h"
35#include "llvm/ADT/Statistic.h"
36#include "llvm/ADT/StringRef.h"
60#include "llvm/IR/CallingConv.h"
61#include "llvm/IR/Constant.h"
62#include "llvm/IR/Constants.h"
63#include "llvm/IR/DataLayout.h"
64#include "llvm/IR/DebugLoc.h"
66#include "llvm/IR/Function.h"
67#include "llvm/IR/GlobalValue.h"
68#include "llvm/IR/IRBuilder.h"
70#include "llvm/IR/Intrinsics.h"
71#include "llvm/IR/IntrinsicsPowerPC.h"
72#include "llvm/IR/Module.h"
73#include "llvm/IR/Type.h"
74#include "llvm/IR/Use.h"
75#include "llvm/IR/Value.h"
76#include "llvm/MC/MCContext.h"
77#include "llvm/MC/MCExpr.h"
87#include "llvm/Support/Debug.h"
89#include "llvm/Support/Format.h"
95#include <algorithm>
96#include <cassert>
97#include <cstdint>
98#include <iterator>
99#include <list>
100#include <optional>
101#include <utility>
102#include <vector>
103
104using namespace llvm;
105
106#define DEBUG_TYPE "ppc-lowering"
107
109 "disable-p10-store-forward",
110 cl::desc("disable P10 store forward-friendly conversion"), cl::Hidden,
111 cl::init(false));
112
113static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
114cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
115
116static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
117cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
118
119static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
120cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
121
122static cl::opt<bool> DisableSCO("disable-ppc-sco",
123cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
124
125static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
126cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
127
128static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
129cl::desc("use absolute jump tables on ppc"), cl::Hidden);
130
131static cl::opt<bool>
132 DisablePerfectShuffle("ppc-disable-perfect-shuffle",
133 cl::desc("disable vector permute decomposition"),
134 cl::init(true), cl::Hidden);
135
137 "disable-auto-paired-vec-st",
138 cl::desc("disable automatically generated 32byte paired vector stores"),
139 cl::init(true), cl::Hidden);
140
142 "ppc-min-jump-table-entries", cl::init(64), cl::Hidden,
143 cl::desc("Set minimum number of entries to use a jump table on PPC"));
144
146 "ppc-gather-alias-max-depth", cl::init(18), cl::Hidden,
147 cl::desc("max depth when checking alias info in GatherAllAliases()"));
148
150 "ppc-aix-shared-lib-tls-model-opt-limit", cl::init(1), cl::Hidden,
151 cl::desc("Set inclusive limit count of TLS local-dynamic access(es) in a "
152 "function to use initial-exec"));
153
154STATISTIC(NumTailCalls, "Number of tail calls");
155STATISTIC(NumSiblingCalls, "Number of sibling calls");
156STATISTIC(ShufflesHandledWithVPERM,
157 "Number of shuffles lowered to a VPERM or XXPERM");
158STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
159
160static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
161
162static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
163
164static const char AIXSSPCanaryWordName[] = "__ssp_canary_word";
165
166// A faster local-[exec|dynamic] TLS access sequence (enabled with the
167// -maix-small-local-[exec|dynamic]-tls option) can be produced for TLS
168// variables; consistent with the IBM XL compiler, we apply a max size of
169// slightly under 32KB.
171
172// FIXME: Remove this once the bug has been fixed!
174
176 const PPCSubtarget &STI)
177 : TargetLowering(TM), Subtarget(STI) {
178 // Initialize map that relates the PPC addressing modes to the computed flags
179 // of a load/store instruction. The map is used to determine the optimal
180 // addressing mode when selecting load and stores.
181 initializeAddrModeMap();
182 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
183 // arguments are at least 4/8 bytes aligned.
184 bool isPPC64 = Subtarget.isPPC64();
185 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
186
187 // Set up the register classes.
188 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
189 if (!useSoftFloat()) {
190 if (hasSPE()) {
191 addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
192 // EFPU2 APU only supports f32
193 if (!Subtarget.hasEFPU2())
194 addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
195 } else {
196 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
197 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
198 }
199 }
200
201 // Match BITREVERSE to customized fast code sequence in the td file.
204
205 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
207
208 // Custom lower inline assembly to check for special registers.
211
212 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
213 for (MVT VT : MVT::integer_valuetypes()) {
216 }
217
218 if (Subtarget.isISA3_0()) {
219 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
220 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
221 setTruncStoreAction(MVT::f64, MVT::f16, Legal);
222 setTruncStoreAction(MVT::f32, MVT::f16, Legal);
223 } else {
224 // No extending loads from f16 or HW conversions back and forth.
225 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
228 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
231 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
232 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
233 }
234
235 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
236
237 // PowerPC has pre-inc load and store's.
248 if (!Subtarget.hasSPE()) {
253 }
254
255 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
256 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
257 for (MVT VT : ScalarIntVTs) {
262 }
263
264 if (Subtarget.useCRBits()) {
266
267 if (isPPC64 || Subtarget.hasFPCVT()) {
270 isPPC64 ? MVT::i64 : MVT::i32);
273 isPPC64 ? MVT::i64 : MVT::i32);
274
277 isPPC64 ? MVT::i64 : MVT::i32);
280 isPPC64 ? MVT::i64 : MVT::i32);
281
284 isPPC64 ? MVT::i64 : MVT::i32);
287 isPPC64 ? MVT::i64 : MVT::i32);
288
291 isPPC64 ? MVT::i64 : MVT::i32);
294 isPPC64 ? MVT::i64 : MVT::i32);
295 } else {
300 }
301
302 // PowerPC does not support direct load/store of condition registers.
305
306 // FIXME: Remove this once the ANDI glue bug is fixed:
307 if (ANDIGlueBug)
309
310 for (MVT VT : MVT::integer_valuetypes()) {
313 setTruncStoreAction(VT, MVT::i1, Expand);
314 }
315
316 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
317 }
318
319 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
320 // PPC (the libcall is not available).
325
326 // We do not currently implement these libm ops for PowerPC.
327 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
328 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
329 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
330 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
332 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
333
334 // PowerPC has no SREM/UREM instructions unless we are on P9
335 // On P9 we may use a hardware instruction to compute the remainder.
336 // When the result of both the remainder and the division is required it is
337 // more efficient to compute the remainder from the result of the division
338 // rather than use the remainder instruction. The instructions are legalized
339 // directly because the DivRemPairsPass performs the transformation at the IR
340 // level.
341 if (Subtarget.isISA3_0()) {
346 } else {
351 }
352
353 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
362
363 // Handle constrained floating-point operations of scalar.
364 // TODO: Handle SPE specific operation.
370
375
376 if (!Subtarget.hasSPE()) {
379 }
380
381 if (Subtarget.hasVSX()) {
384 }
385
386 if (Subtarget.hasFSQRT()) {
389 }
390
391 if (Subtarget.hasFPRND()) {
396
401 }
402
403 // We don't support sin/cos/sqrt/fmod/pow
414
415 // MASS transformation for LLVM intrinsics with replicating fast-math flag
416 // to be consistent to PPCGenScalarMASSEntries pass
417 if (TM.getOptLevel() == CodeGenOptLevel::Aggressive) {
430 }
431
432 if (Subtarget.hasSPE()) {
435 } else {
436 setOperationAction(ISD::FMA , MVT::f64, Legal);
437 setOperationAction(ISD::FMA , MVT::f32, Legal);
438 }
439
440 if (Subtarget.hasSPE())
441 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
442
444
445 // If we're enabling GP optimizations, use hardware square root
446 if (!Subtarget.hasFSQRT() &&
447 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
448 Subtarget.hasFRE()))
450
451 if (!Subtarget.hasFSQRT() &&
452 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
453 Subtarget.hasFRES()))
455
456 if (Subtarget.hasFCPSGN()) {
459 } else {
462 }
463
464 if (Subtarget.hasFPRND()) {
469
474 }
475
476 // Prior to P10, PowerPC does not have BSWAP, but we can use vector BSWAP
477 // instruction xxbrd to speed up scalar BSWAP64.
478 if (Subtarget.isISA3_1()) {
481 } else {
484 ISD::BSWAP, MVT::i64,
485 (Subtarget.hasP9Vector() && Subtarget.isPPC64()) ? Custom : Expand);
486 }
487
488 // CTPOP or CTTZ were introduced in P8/P9 respectively
489 if (Subtarget.isISA3_0()) {
490 setOperationAction(ISD::CTTZ , MVT::i32 , Legal);
491 setOperationAction(ISD::CTTZ , MVT::i64 , Legal);
492 } else {
493 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
494 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
495 }
496
497 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
500 } else {
503 }
504
505 // PowerPC does not have ROTR
508
509 if (!Subtarget.useCRBits()) {
510 // PowerPC does not have Select
515 }
516
517 // PowerPC wants to turn select_cc of FP into fsel when possible.
520
521 // PowerPC wants to optimize integer setcc a bit
522 if (!Subtarget.useCRBits())
524
525 if (Subtarget.hasFPU()) {
529
533 }
534
535 // PowerPC does not have BRCOND which requires SetCC
536 if (!Subtarget.useCRBits())
538
540
541 if (Subtarget.hasSPE()) {
542 // SPE has built-in conversions
549
550 // SPE supports signaling compare of f32/f64.
553 } else {
554 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
557
558 // PowerPC does not have [U|S]INT_TO_FP
563 }
564
565 if (Subtarget.hasDirectMove() && isPPC64) {
570 if (TM.Options.UnsafeFPMath) {
579 }
580 } else {
585 }
586
587 // We cannot sextinreg(i1). Expand to shifts.
589
590 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
591 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
592 // support continuation, user-level threading, and etc.. As a result, no
593 // other SjLj exception interfaces are implemented and please don't build
594 // your own exception handling based on them.
595 // LLVM/Clang supports zero-cost DWARF exception handling.
598
599 // We want to legalize GlobalAddress and ConstantPool nodes into the
600 // appropriate instructions to materialize the address.
611
612 // TRAP is legal.
613 setOperationAction(ISD::TRAP, MVT::Other, Legal);
614
615 // TRAMPOLINE is custom lowered.
618
619 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
621
622 if (Subtarget.is64BitELFABI()) {
623 // VAARG always uses double-word chunks, so promote anything smaller.
625 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
627 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
629 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
631 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
633 } else if (Subtarget.is32BitELFABI()) {
634 // VAARG is custom lowered with the 32-bit SVR4 ABI.
637 } else
639
640 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
641 if (Subtarget.is32BitELFABI())
643 else
645
646 // Use the default implementation.
647 setOperationAction(ISD::VAEND , MVT::Other, Expand);
656
657 // We want to custom lower some of our intrinsics.
663
664 // To handle counter-based loop conditions.
666
671
672 // Comparisons that require checking two conditions.
673 if (Subtarget.hasSPE()) {
678 }
691
694
695 if (Subtarget.has64BitSupport()) {
696 // They also have instructions for converting between i64 and fp.
705 // This is just the low 32 bits of a (signed) fp->i64 conversion.
706 // We cannot do this with Promote because i64 is not a legal type.
709
710 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
713 }
714 } else {
715 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
716 if (Subtarget.hasSPE()) {
719 } else {
722 }
723 }
724
725 // With the instructions enabled under FPCVT, we can do everything.
726 if (Subtarget.hasFPCVT()) {
727 if (Subtarget.has64BitSupport()) {
736 }
737
746 }
747
748 if (Subtarget.use64BitRegs()) {
749 // 64-bit PowerPC implementations can support i64 types directly
750 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
751 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
753 // 64-bit PowerPC wants to expand i128 shifts itself.
757 } else {
758 // 32-bit PowerPC wants to expand i64 shifts itself.
762 }
763
764 // PowerPC has better expansions for funnel shifts than the generic
765 // TargetLowering::expandFunnelShift.
766 if (Subtarget.has64BitSupport()) {
769 }
772
773 if (Subtarget.hasVSX()) {
778 }
779
780 if (Subtarget.hasAltivec()) {
781 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
786 }
787 // First set operation action for all vector types to expand. Then we
788 // will selectively turn on ones that can be effectively codegen'd.
790 // add/sub are legal for all supported vector VT's.
793
794 // For v2i64, these are only valid with P8Vector. This is corrected after
795 // the loop.
796 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
801 }
802 else {
807 }
808
809 if (Subtarget.hasVSX()) {
812 }
813
814 // Vector instructions introduced in P8
815 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
818 }
819 else {
822 }
823
824 // Vector instructions introduced in P9
825 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
827 else
829
830 // We promote all shuffles to v16i8.
832 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
833
834 // We promote all non-typed operations to v4i32.
836 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
838 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
840 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
842 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
844 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
847 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
849 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
850
851 // No other operations are legal.
890
891 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
892 setTruncStoreAction(VT, InnerVT, Expand);
895 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
896 }
897 }
899 if (!Subtarget.hasP8Vector()) {
900 setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
901 setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
902 setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
903 setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
904 }
905
906 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
907 // with merges, splats, etc.
909
910 // Vector truncates to sub-word integer that fit in an Altivec/VSX register
911 // are cheap, so handle them before they get expanded to scalar.
917
918 setOperationAction(ISD::AND , MVT::v4i32, Legal);
919 setOperationAction(ISD::OR , MVT::v4i32, Legal);
920 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
921 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
923 Subtarget.useCRBits() ? Legal : Expand);
924 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
934 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
937
938 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
939 setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
940 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
941 if (Subtarget.hasAltivec())
942 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
944 // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
945 if (Subtarget.hasP8Altivec())
946 setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
947
948 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
949 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
950 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
951 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
952
953 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
954 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
955
956 if (Subtarget.hasVSX()) {
957 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
958 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
960 }
961
962 if (Subtarget.hasP8Altivec())
963 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
964 else
965 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
966
967 if (Subtarget.isISA3_1()) {
968 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
969 setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
970 setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
971 setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
972 setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
973 setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
974 setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
975 setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
976 setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
977 setOperationAction(ISD::UREM, MVT::v2i64, Legal);
978 setOperationAction(ISD::SREM, MVT::v2i64, Legal);
979 setOperationAction(ISD::UREM, MVT::v4i32, Legal);
980 setOperationAction(ISD::SREM, MVT::v4i32, Legal);
981 setOperationAction(ISD::UREM, MVT::v1i128, Legal);
982 setOperationAction(ISD::SREM, MVT::v1i128, Legal);
983 setOperationAction(ISD::UDIV, MVT::v1i128, Legal);
984 setOperationAction(ISD::SDIV, MVT::v1i128, Legal);
985 setOperationAction(ISD::ROTL, MVT::v1i128, Legal);
986 }
987
988 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
989 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
990
993 // LE is P8+/64-bit so direct moves are supported and these operations
994 // are legal. The custom transformation requires 64-bit since we need a
995 // pair of stores that will cover a 128-bit load for P10.
996 if (!DisableP10StoreForward && isPPC64 && !Subtarget.isLittleEndian()) {
1000 }
1001
1006
1007 // Altivec does not contain unordered floating-point compare instructions
1008 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
1009 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
1010 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
1011 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
1012
1013 if (Subtarget.hasVSX()) {
1016 if (Subtarget.hasP8Vector()) {
1019 }
1020 if (Subtarget.hasDirectMove() && isPPC64) {
1029 }
1031
1032 // The nearbyint variants are not allowed to raise the inexact exception
1033 // so we can only code-gen them with unsafe math.
1034 if (TM.Options.UnsafeFPMath) {
1037 }
1038
1039 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1040 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1041 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1043 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1044 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
1047
1049 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1050 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1053
1054 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
1055 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1056
1057 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
1058 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
1059
1060 // Share the Altivec comparison restrictions.
1061 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
1062 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
1063 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
1064 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
1065
1066 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1067 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
1068
1070
1071 if (Subtarget.hasP8Vector())
1072 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
1073
1074 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
1075
1076 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
1077 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
1078 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
1079
1080 if (Subtarget.hasP8Altivec()) {
1081 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1082 setOperationAction(ISD::SRA, MVT::v2i64, Legal);
1083 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1084
1085 // 128 bit shifts can be accomplished via 3 instructions for SHL and
1086 // SRL, but not for SRA because of the instructions available:
1087 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
1088 // doing
1089 setOperationAction(ISD::SHL, MVT::v1i128, Expand);
1090 setOperationAction(ISD::SRL, MVT::v1i128, Expand);
1091 setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1092
1093 setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
1094 }
1095 else {
1096 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
1097 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
1098 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
1099
1100 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1101
1102 // VSX v2i64 only supports non-arithmetic operations.
1103 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
1104 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
1105 }
1106
1107 if (Subtarget.isISA3_1())
1108 setOperationAction(ISD::SETCC, MVT::v1i128, Legal);
1109 else
1110 setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1111
1112 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1113 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1115 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1116
1118
1127
1128 // Custom handling for partial vectors of integers converted to
1129 // floating point. We already have optimal handling for v2i32 through
1130 // the DAG combine, so those aren't necessary.
1147
1148 setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1149 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1150 setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1151 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1154
1157
1158 // Handle constrained floating-point operations of vector.
1159 // The predictor is `hasVSX` because altivec instruction has
1160 // no exception but VSX vector instruction has.
1174
1188
1189 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1190 addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1191
1192 for (MVT FPT : MVT::fp_valuetypes())
1193 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1194
1195 // Expand the SELECT to SELECT_CC
1197
1198 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1199 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1200
1201 // No implementation for these ops for PowerPC.
1203 setOperationAction(ISD::FSIN, MVT::f128, Expand);
1204 setOperationAction(ISD::FCOS, MVT::f128, Expand);
1205 setOperationAction(ISD::FPOW, MVT::f128, Expand);
1207 setOperationAction(ISD::FREM, MVT::f128, Expand);
1208 }
1209
1210 if (Subtarget.hasP8Altivec()) {
1211 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1212 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1213 }
1214
1215 if (Subtarget.hasP9Vector()) {
1218
1219 // Test data class instructions store results in CR bits.
1220 if (Subtarget.useCRBits()) {
1224 }
1225
1226 // 128 bit shifts can be accomplished via 3 instructions for SHL and
1227 // SRL, but not for SRA because of the instructions available:
1228 // VS{RL} and VS{RL}O.
1229 setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1230 setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1231 setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1232
1233 setOperationAction(ISD::FADD, MVT::f128, Legal);
1234 setOperationAction(ISD::FSUB, MVT::f128, Legal);
1235 setOperationAction(ISD::FDIV, MVT::f128, Legal);
1236 setOperationAction(ISD::FMUL, MVT::f128, Legal);
1238
1239 setOperationAction(ISD::FMA, MVT::f128, Legal);
1246
1248 setOperationAction(ISD::FRINT, MVT::f128, Legal);
1250 setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1253
1257
1258 // Handle constrained floating-point operations of fp128
1275 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1276 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1277 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1278 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1279 } else if (Subtarget.hasVSX()) {
1282
1283 AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32);
1284 AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32);
1285
1286 // Set FADD/FSUB as libcall to avoid the legalizer to expand the
1287 // fp_to_uint and int_to_fp.
1290
1291 setOperationAction(ISD::FMUL, MVT::f128, Expand);
1292 setOperationAction(ISD::FDIV, MVT::f128, Expand);
1293 setOperationAction(ISD::FNEG, MVT::f128, Expand);
1294 setOperationAction(ISD::FABS, MVT::f128, Expand);
1296 setOperationAction(ISD::FMA, MVT::f128, Expand);
1298
1299 // Expand the fp_extend if the target type is fp128.
1302
1303 // Expand the fp_round if the source type is fp128.
1304 for (MVT VT : {MVT::f32, MVT::f64}) {
1307 }
1308
1313
1314 // Lower following f128 select_cc pattern:
1315 // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE
1317
1318 // We need to handle f128 SELECT_CC with integer result type.
1320 setOperationAction(ISD::SELECT_CC, MVT::i64, isPPC64 ? Custom : Expand);
1321 }
1322
1323 if (Subtarget.hasP9Altivec()) {
1324 if (Subtarget.isISA3_1()) {
1329 } else {
1332 }
1340
1341 setOperationAction(ISD::ABDU, MVT::v16i8, Legal);
1342 setOperationAction(ISD::ABDU, MVT::v8i16, Legal);
1343 setOperationAction(ISD::ABDU, MVT::v4i32, Legal);
1344 setOperationAction(ISD::ABDS, MVT::v4i32, Legal);
1345 }
1346
1347 if (Subtarget.hasP10Vector()) {
1349 }
1350 }
1351
1352 if (Subtarget.pairedVectorMemops()) {
1353 addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1354 setOperationAction(ISD::LOAD, MVT::v256i1, Custom);
1355 setOperationAction(ISD::STORE, MVT::v256i1, Custom);
1356 }
1357 if (Subtarget.hasMMA()) {
1358 if (Subtarget.isISAFuture())
1359 addRegisterClass(MVT::v512i1, &PPC::WACCRCRegClass);
1360 else
1361 addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1362 setOperationAction(ISD::LOAD, MVT::v512i1, Custom);
1363 setOperationAction(ISD::STORE, MVT::v512i1, Custom);
1365 }
1366
1367 if (Subtarget.has64BitSupport())
1369
1370 if (Subtarget.isISA3_1())
1371 setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1372
1373 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1374
1375 if (!isPPC64) {
1378 }
1379
1384 }
1385
1387
1388 if (Subtarget.hasAltivec()) {
1389 // Altivec instructions set fields to all zeros or all ones.
1391 }
1392
1395 else if (isPPC64)
1397 else
1399
1400 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1401
1402 // We have target-specific dag combine patterns for the following nodes:
1405 if (Subtarget.hasFPCVT())
1408 if (Subtarget.useCRBits())
1412
1414
1416
1417 if (Subtarget.useCRBits()) {
1419 }
1420
1421 setLibcallName(RTLIB::LOG_F128, "logf128");
1422 setLibcallName(RTLIB::LOG2_F128, "log2f128");
1423 setLibcallName(RTLIB::LOG10_F128, "log10f128");
1424 setLibcallName(RTLIB::EXP_F128, "expf128");
1425 setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1426 setLibcallName(RTLIB::SIN_F128, "sinf128");
1427 setLibcallName(RTLIB::COS_F128, "cosf128");
1428 setLibcallName(RTLIB::SINCOS_F128, "sincosf128");
1429 setLibcallName(RTLIB::POW_F128, "powf128");
1430 setLibcallName(RTLIB::FMIN_F128, "fminf128");
1431 setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1432 setLibcallName(RTLIB::REM_F128, "fmodf128");
1433 setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
1434 setLibcallName(RTLIB::CEIL_F128, "ceilf128");
1435 setLibcallName(RTLIB::FLOOR_F128, "floorf128");
1436 setLibcallName(RTLIB::TRUNC_F128, "truncf128");
1437 setLibcallName(RTLIB::ROUND_F128, "roundf128");
1438 setLibcallName(RTLIB::LROUND_F128, "lroundf128");
1439 setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
1440 setLibcallName(RTLIB::RINT_F128, "rintf128");
1441 setLibcallName(RTLIB::LRINT_F128, "lrintf128");
1442 setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
1443 setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
1444 setLibcallName(RTLIB::FMA_F128, "fmaf128");
1445 setLibcallName(RTLIB::FREXP_F128, "frexpf128");
1446
1447 if (Subtarget.isAIXABI()) {
1448 setLibcallName(RTLIB::MEMCPY, isPPC64 ? "___memmove64" : "___memmove");
1449 setLibcallName(RTLIB::MEMMOVE, isPPC64 ? "___memmove64" : "___memmove");
1450 setLibcallName(RTLIB::MEMSET, isPPC64 ? "___memset64" : "___memset");
1451 setLibcallName(RTLIB::BZERO, isPPC64 ? "___bzero64" : "___bzero");
1452 }
1453
1454 // With 32 condition bits, we don't need to sink (and duplicate) compares
1455 // aggressively in CodeGenPrep.
1456 if (Subtarget.useCRBits()) {
1459 }
1460
1461 // TODO: The default entry number is set to 64. This stops most jump table
1462 // generation on PPC. But it is good for current PPC HWs because the indirect
1463 // branch instruction mtctr to the jump table may lead to bad branch predict.
1464 // Re-evaluate this value on future HWs that can do better with mtctr.
1466
1468
1469 switch (Subtarget.getCPUDirective()) {
1470 default: break;
1471 case PPC::DIR_970:
1472 case PPC::DIR_A2:
1473 case PPC::DIR_E500:
1474 case PPC::DIR_E500mc:
1475 case PPC::DIR_E5500:
1476 case PPC::DIR_PWR4:
1477 case PPC::DIR_PWR5:
1478 case PPC::DIR_PWR5X:
1479 case PPC::DIR_PWR6:
1480 case PPC::DIR_PWR6X:
1481 case PPC::DIR_PWR7:
1482 case PPC::DIR_PWR8:
1483 case PPC::DIR_PWR9:
1484 case PPC::DIR_PWR10:
1485 case PPC::DIR_PWR11:
1489 break;
1490 }
1491
1492 if (Subtarget.enableMachineScheduler())
1494 else
1496
1498
1499 // The Freescale cores do better with aggressive inlining of memcpy and
1500 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1501 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1502 Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1503 MaxStoresPerMemset = 32;
1505 MaxStoresPerMemcpy = 32;
1509 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1510 // The A2 also benefits from (very) aggressive inlining of memcpy and
1511 // friends. The overhead of a the function call, even when warm, can be
1512 // over one hundred cycles.
1513 MaxStoresPerMemset = 128;
1514 MaxStoresPerMemcpy = 128;
1515 MaxStoresPerMemmove = 128;
1516 MaxLoadsPerMemcmp = 128;
1517 } else {
1520 }
1521
1522 IsStrictFPEnabled = true;
1523
1524 // Let the subtarget (CPU) decide if a predictable select is more expensive
1525 // than the corresponding branch. This information is used in CGP to decide
1526 // when to convert selects into branches.
1528
1530}
1531
1532// *********************************** NOTE ************************************
1533// For selecting load and store instructions, the addressing modes are defined
1534// as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD
1535// patterns to match the load the store instructions.
1536//
1537// The TD definitions for the addressing modes correspond to their respective
1538// Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely
1539// on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the
1540// address mode flags of a particular node. Afterwards, the computed address
1541// flags are passed into getAddrModeForFlags() in order to retrieve the optimal
1542// addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement
1543// accordingly, based on the preferred addressing mode.
1544//
1545// Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode.
1546// MemOpFlags contains all the possible flags that can be used to compute the
1547// optimal addressing mode for load and store instructions.
1548// AddrMode contains all the possible load and store addressing modes available
1549// on Power (such as DForm, DSForm, DQForm, XForm, etc.)
1550//
1551// When adding new load and store instructions, it is possible that new address
1552// flags may need to be added into MemOpFlags, and a new addressing mode will
1553// need to be added to AddrMode. An entry of the new addressing mode (consisting
1554// of the minimal and main distinguishing address flags for the new load/store
1555// instructions) will need to be added into initializeAddrModeMap() below.
1556// Finally, when adding new addressing modes, the getAddrModeForFlags() will
1557// need to be updated to account for selecting the optimal addressing mode.
1558// *****************************************************************************
1559/// Initialize the map that relates the different addressing modes of the load
1560/// and store instructions to a set of flags. This ensures the load/store
1561/// instruction is correctly matched during instruction selection.
1562void PPCTargetLowering::initializeAddrModeMap() {
1563 AddrModesMap[PPC::AM_DForm] = {
1564 // LWZ, STW
1569 // LBZ, LHZ, STB, STH
1574 // LHA
1579 // LFS, LFD, STFS, STFD
1584 };
1585 AddrModesMap[PPC::AM_DSForm] = {
1586 // LWA
1590 // LD, STD
1594 // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64
1598 };
1599 AddrModesMap[PPC::AM_DQForm] = {
1600 // LXV, STXV
1604 };
1605 AddrModesMap[PPC::AM_PrefixDForm] = {PPC::MOF_RPlusSImm34 |
1607 // TODO: Add mapping for quadword load/store.
1608}
1609
1610/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1611/// the desired ByVal argument alignment.
1612static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1613 if (MaxAlign == MaxMaxAlign)
1614 return;
1615 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1616 if (MaxMaxAlign >= 32 &&
1617 VTy->getPrimitiveSizeInBits().getFixedValue() >= 256)
1618 MaxAlign = Align(32);
1619 else if (VTy->getPrimitiveSizeInBits().getFixedValue() >= 128 &&
1620 MaxAlign < 16)
1621 MaxAlign = Align(16);
1622 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1623 Align EltAlign;
1624 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1625 if (EltAlign > MaxAlign)
1626 MaxAlign = EltAlign;
1627 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1628 for (auto *EltTy : STy->elements()) {
1629 Align EltAlign;
1630 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1631 if (EltAlign > MaxAlign)
1632 MaxAlign = EltAlign;
1633 if (MaxAlign == MaxMaxAlign)
1634 break;
1635 }
1636 }
1637}
1638
1639/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1640/// function arguments in the caller parameter area.
1642 const DataLayout &DL) const {
1643 // 16byte and wider vectors are passed on 16byte boundary.
1644 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1645 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1646 if (Subtarget.hasAltivec())
1647 getMaxByValAlign(Ty, Alignment, Align(16));
1648 return Alignment.value();
1649}
1650
1652 return Subtarget.useSoftFloat();
1653}
1654
1656 return Subtarget.hasSPE();
1657}
1658
1660 return VT.isScalarInteger();
1661}
1662
1664 Type *VectorTy, unsigned ElemSizeInBits, unsigned &Index) const {
1665 if (!Subtarget.isPPC64() || !Subtarget.hasVSX())
1666 return false;
1667
1668 if (auto *VTy = dyn_cast<VectorType>(VectorTy)) {
1669 if (VTy->getScalarType()->isIntegerTy()) {
1670 // ElemSizeInBits 8/16 can fit in immediate field, not needed here.
1671 if (ElemSizeInBits == 32) {
1672 Index = Subtarget.isLittleEndian() ? 2 : 1;
1673 return true;
1674 }
1675 if (ElemSizeInBits == 64) {
1676 Index = Subtarget.isLittleEndian() ? 1 : 0;
1677 return true;
1678 }
1679 }
1680 }
1681 return false;
1682}
1683
1684const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1685 switch ((PPCISD::NodeType)Opcode) {
1686 case PPCISD::FIRST_NUMBER: break;
1687 case PPCISD::FSEL: return "PPCISD::FSEL";
1688 case PPCISD::XSMAXC: return "PPCISD::XSMAXC";
1689 case PPCISD::XSMINC: return "PPCISD::XSMINC";
1690 case PPCISD::FCFID: return "PPCISD::FCFID";
1691 case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
1692 case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
1693 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
1694 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
1695 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
1696 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
1697 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
1698 case PPCISD::FRE: return "PPCISD::FRE";
1699 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
1700 case PPCISD::FTSQRT:
1701 return "PPCISD::FTSQRT";
1702 case PPCISD::FSQRT:
1703 return "PPCISD::FSQRT";
1704 case PPCISD::STFIWX: return "PPCISD::STFIWX";
1705 case PPCISD::VPERM: return "PPCISD::VPERM";
1706 case PPCISD::XXSPLT: return "PPCISD::XXSPLT";
1708 return "PPCISD::XXSPLTI_SP_TO_DP";
1710 return "PPCISD::XXSPLTI32DX";
1711 case PPCISD::VECINSERT: return "PPCISD::VECINSERT";
1712 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI";
1713 case PPCISD::XXPERM:
1714 return "PPCISD::XXPERM";
1715 case PPCISD::VECSHL: return "PPCISD::VECSHL";
1716 case PPCISD::CMPB: return "PPCISD::CMPB";
1717 case PPCISD::Hi: return "PPCISD::Hi";
1718 case PPCISD::Lo: return "PPCISD::Lo";
1719 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
1720 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1721 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1722 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
1723 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET";
1724 case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA";
1725 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
1726 case PPCISD::SRL: return "PPCISD::SRL";
1727 case PPCISD::SRA: return "PPCISD::SRA";
1728 case PPCISD::SHL: return "PPCISD::SHL";
1729 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE";
1730 case PPCISD::CALL: return "PPCISD::CALL";
1731 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
1732 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC";
1733 case PPCISD::CALL_RM:
1734 return "PPCISD::CALL_RM";
1736 return "PPCISD::CALL_NOP_RM";
1738 return "PPCISD::CALL_NOTOC_RM";
1739 case PPCISD::MTCTR: return "PPCISD::MTCTR";
1740 case PPCISD::BCTRL: return "PPCISD::BCTRL";
1741 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
1742 case PPCISD::BCTRL_RM:
1743 return "PPCISD::BCTRL_RM";
1745 return "PPCISD::BCTRL_LOAD_TOC_RM";
1746 case PPCISD::RET_GLUE: return "PPCISD::RET_GLUE";
1747 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
1748 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
1749 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1750 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
1751 case PPCISD::MFVSR: return "PPCISD::MFVSR";
1752 case PPCISD::MTVSRA: return "PPCISD::MTVSRA";
1753 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ";
1754 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP";
1755 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP";
1757 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1759 return "PPCISD::ANDI_rec_1_EQ_BIT";
1761 return "PPCISD::ANDI_rec_1_GT_BIT";
1762 case PPCISD::VCMP: return "PPCISD::VCMP";
1763 case PPCISD::VCMP_rec: return "PPCISD::VCMP_rec";
1764 case PPCISD::LBRX: return "PPCISD::LBRX";
1765 case PPCISD::STBRX: return "PPCISD::STBRX";
1766 case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
1767 case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
1768 case PPCISD::LXSIZX: return "PPCISD::LXSIZX";
1769 case PPCISD::STXSIX: return "PPCISD::STXSIX";
1770 case PPCISD::VEXTS: return "PPCISD::VEXTS";
1771 case PPCISD::LXVD2X: return "PPCISD::LXVD2X";
1772 case PPCISD::STXVD2X: return "PPCISD::STXVD2X";
1773 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE";
1774 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE";
1776 return "PPCISD::ST_VSR_SCAL_INT";
1777 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
1778 case PPCISD::BDNZ: return "PPCISD::BDNZ";
1779 case PPCISD::BDZ: return "PPCISD::BDZ";
1780 case PPCISD::MFFS: return "PPCISD::MFFS";
1781 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
1782 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
1783 case PPCISD::CR6SET: return "PPCISD::CR6SET";
1784 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
1785 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
1786 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT";
1787 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1788 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
1789 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
1790 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
1791 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
1792 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
1793 case PPCISD::GET_TLS_MOD_AIX: return "PPCISD::GET_TLS_MOD_AIX";
1794 case PPCISD::GET_TPOINTER: return "PPCISD::GET_TPOINTER";
1795 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1796 case PPCISD::TLSGD_AIX: return "PPCISD::TLSGD_AIX";
1797 case PPCISD::TLSLD_AIX: return "PPCISD::TLSLD_AIX";
1798 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
1799 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
1800 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
1801 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1802 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1803 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
1805 return "PPCISD::PADDI_DTPREL";
1806 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
1807 case PPCISD::SC: return "PPCISD::SC";
1808 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB";
1809 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE";
1810 case PPCISD::RFEBB: return "PPCISD::RFEBB";
1811 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD";
1812 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN";
1813 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128";
1814 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64";
1815 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE";
1816 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI";
1817 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH";
1818 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF";
1819 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR";
1821 return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1823 return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1824 case PPCISD::ACC_BUILD: return "PPCISD::ACC_BUILD";
1825 case PPCISD::PAIR_BUILD: return "PPCISD::PAIR_BUILD";
1826 case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1827 case PPCISD::XXMFACC: return "PPCISD::XXMFACC";
1828 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT";
1829 case PPCISD::ZEXT_LD_SPLAT: return "PPCISD::ZEXT_LD_SPLAT";
1830 case PPCISD::SEXT_LD_SPLAT: return "PPCISD::SEXT_LD_SPLAT";
1831 case PPCISD::FNMSUB: return "PPCISD::FNMSUB";
1833 return "PPCISD::STRICT_FADDRTZ";
1835 return "PPCISD::STRICT_FCTIDZ";
1837 return "PPCISD::STRICT_FCTIWZ";
1839 return "PPCISD::STRICT_FCTIDUZ";
1841 return "PPCISD::STRICT_FCTIWUZ";
1843 return "PPCISD::STRICT_FCFID";
1845 return "PPCISD::STRICT_FCFIDU";
1847 return "PPCISD::STRICT_FCFIDS";
1849 return "PPCISD::STRICT_FCFIDUS";
1850 case PPCISD::LXVRZX: return "PPCISD::LXVRZX";
1851 case PPCISD::STORE_COND:
1852 return "PPCISD::STORE_COND";
1853 }
1854 return nullptr;
1855}
1856
1858 EVT VT) const {
1859 if (!VT.isVector())
1860 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1861
1863}
1864
1866 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1867 return true;
1868}
1869
1870//===----------------------------------------------------------------------===//
1871// Node matching predicates, for use by the tblgen matching code.
1872//===----------------------------------------------------------------------===//
1873
1874/// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1876 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1877 return CFP->getValueAPF().isZero();
1878 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1879 // Maybe this has already been legalized into the constant pool?
1880 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1881 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1882 return CFP->getValueAPF().isZero();
1883 }
1884 return false;
1885}
1886
1887/// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1888/// true if Op is undef or if it matches the specified value.
1889static bool isConstantOrUndef(int Op, int Val) {
1890 return Op < 0 || Op == Val;
1891}
1892
1893/// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1894/// VPKUHUM instruction.
1895/// The ShuffleKind distinguishes between big-endian operations with
1896/// two different inputs (0), either-endian operations with two identical
1897/// inputs (1), and little-endian operations with two different inputs (2).
1898/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1900 SelectionDAG &DAG) {
1901 bool IsLE = DAG.getDataLayout().isLittleEndian();
1902 if (ShuffleKind == 0) {
1903 if (IsLE)
1904 return false;
1905 for (unsigned i = 0; i != 16; ++i)
1906 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1907 return false;
1908 } else if (ShuffleKind == 2) {
1909 if (!IsLE)
1910 return false;
1911 for (unsigned i = 0; i != 16; ++i)
1912 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1913 return false;
1914 } else if (ShuffleKind == 1) {
1915 unsigned j = IsLE ? 0 : 1;
1916 for (unsigned i = 0; i != 8; ++i)
1917 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1918 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1919 return false;
1920 }
1921 return true;
1922}
1923
1924/// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1925/// VPKUWUM instruction.
1926/// The ShuffleKind distinguishes between big-endian operations with
1927/// two different inputs (0), either-endian operations with two identical
1928/// inputs (1), and little-endian operations with two different inputs (2).
1929/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1931 SelectionDAG &DAG) {
1932 bool IsLE = DAG.getDataLayout().isLittleEndian();
1933 if (ShuffleKind == 0) {
1934 if (IsLE)
1935 return false;
1936 for (unsigned i = 0; i != 16; i += 2)
1937 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1938 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1939 return false;
1940 } else if (ShuffleKind == 2) {
1941 if (!IsLE)
1942 return false;
1943 for (unsigned i = 0; i != 16; i += 2)
1944 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1945 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1946 return false;
1947 } else if (ShuffleKind == 1) {
1948 unsigned j = IsLE ? 0 : 2;
1949 for (unsigned i = 0; i != 8; i += 2)
1950 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1951 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1952 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1953 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1954 return false;
1955 }
1956 return true;
1957}
1958
1959/// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1960/// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1961/// current subtarget.
1962///
1963/// The ShuffleKind distinguishes between big-endian operations with
1964/// two different inputs (0), either-endian operations with two identical
1965/// inputs (1), and little-endian operations with two different inputs (2).
1966/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1968 SelectionDAG &DAG) {
1969 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>();
1970 if (!Subtarget.hasP8Vector())
1971 return false;
1972
1973 bool IsLE = DAG.getDataLayout().isLittleEndian();
1974 if (ShuffleKind == 0) {
1975 if (IsLE)
1976 return false;
1977 for (unsigned i = 0; i != 16; i += 4)
1978 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) ||
1979 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) ||
1980 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) ||
1981 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7))
1982 return false;
1983 } else if (ShuffleKind == 2) {
1984 if (!IsLE)
1985 return false;
1986 for (unsigned i = 0; i != 16; i += 4)
1987 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1988 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) ||
1989 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) ||
1990 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3))
1991 return false;
1992 } else if (ShuffleKind == 1) {
1993 unsigned j = IsLE ? 0 : 4;
1994 for (unsigned i = 0; i != 8; i += 4)
1995 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1996 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1997 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) ||
1998 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) ||
1999 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
2000 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) ||
2001 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
2002 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
2003 return false;
2004 }
2005 return true;
2006}
2007
2008/// isVMerge - Common function, used to match vmrg* shuffles.
2009///
2010static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
2011 unsigned LHSStart, unsigned RHSStart) {
2012 if (N->getValueType(0) != MVT::v16i8)
2013 return false;
2014 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
2015 "Unsupported merge size!");
2016
2017 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
2018 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
2019 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
2020 LHSStart+j+i*UnitSize) ||
2021 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
2022 RHSStart+j+i*UnitSize))
2023 return false;
2024 }
2025 return true;
2026}
2027
2028/// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
2029/// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
2030/// The ShuffleKind distinguishes between big-endian merges with two
2031/// different inputs (0), either-endian merges with two identical inputs (1),
2032/// and little-endian merges with two different inputs (2). For the latter,
2033/// the input operands are swapped (see PPCInstrAltivec.td).
2035 unsigned ShuffleKind, SelectionDAG &DAG) {
2036 if (DAG.getDataLayout().isLittleEndian()) {
2037 if (ShuffleKind == 1) // unary
2038 return isVMerge(N, UnitSize, 0, 0);
2039 else if (ShuffleKind == 2) // swapped
2040 return isVMerge(N, UnitSize, 0, 16);
2041 else
2042 return false;
2043 } else {
2044 if (ShuffleKind == 1) // unary
2045 return isVMerge(N, UnitSize, 8, 8);
2046 else if (ShuffleKind == 0) // normal
2047 return isVMerge(N, UnitSize, 8, 24);
2048 else
2049 return false;
2050 }
2051}
2052
2053/// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
2054/// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
2055/// The ShuffleKind distinguishes between big-endian merges with two
2056/// different inputs (0), either-endian merges with two identical inputs (1),
2057/// and little-endian merges with two different inputs (2). For the latter,
2058/// the input operands are swapped (see PPCInstrAltivec.td).
2060 unsigned ShuffleKind, SelectionDAG &DAG) {
2061 if (DAG.getDataLayout().isLittleEndian()) {
2062 if (ShuffleKind == 1) // unary
2063 return isVMerge(N, UnitSize, 8, 8);
2064 else if (ShuffleKind == 2) // swapped
2065 return isVMerge(N, UnitSize, 8, 24);
2066 else
2067 return false;
2068 } else {
2069 if (ShuffleKind == 1) // unary
2070 return isVMerge(N, UnitSize, 0, 0);
2071 else if (ShuffleKind == 0) // normal
2072 return isVMerge(N, UnitSize, 0, 16);
2073 else
2074 return false;
2075 }
2076}
2077
2078/**
2079 * Common function used to match vmrgew and vmrgow shuffles
2080 *
2081 * The indexOffset determines whether to look for even or odd words in
2082 * the shuffle mask. This is based on the of the endianness of the target
2083 * machine.
2084 * - Little Endian:
2085 * - Use offset of 0 to check for odd elements
2086 * - Use offset of 4 to check for even elements
2087 * - Big Endian:
2088 * - Use offset of 0 to check for even elements
2089 * - Use offset of 4 to check for odd elements
2090 * A detailed description of the vector element ordering for little endian and
2091 * big endian can be found at
2092 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
2093 * Targeting your applications - what little endian and big endian IBM XL C/C++
2094 * compiler differences mean to you
2095 *
2096 * The mask to the shuffle vector instruction specifies the indices of the
2097 * elements from the two input vectors to place in the result. The elements are
2098 * numbered in array-access order, starting with the first vector. These vectors
2099 * are always of type v16i8, thus each vector will contain 16 elements of size
2100 * 8. More info on the shuffle vector can be found in the
2101 * http://llvm.org/docs/LangRef.html#shufflevector-instruction
2102 * Language Reference.
2103 *
2104 * The RHSStartValue indicates whether the same input vectors are used (unary)
2105 * or two different input vectors are used, based on the following:
2106 * - If the instruction uses the same vector for both inputs, the range of the
2107 * indices will be 0 to 15. In this case, the RHSStart value passed should
2108 * be 0.
2109 * - If the instruction has two different vectors then the range of the
2110 * indices will be 0 to 31. In this case, the RHSStart value passed should
2111 * be 16 (indices 0-15 specify elements in the first vector while indices 16
2112 * to 31 specify elements in the second vector).
2113 *
2114 * \param[in] N The shuffle vector SD Node to analyze
2115 * \param[in] IndexOffset Specifies whether to look for even or odd elements
2116 * \param[in] RHSStartValue Specifies the starting index for the righthand input
2117 * vector to the shuffle_vector instruction
2118 * \return true iff this shuffle vector represents an even or odd word merge
2119 */
2120static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
2121 unsigned RHSStartValue) {
2122 if (N->getValueType(0) != MVT::v16i8)
2123 return false;
2124
2125 for (unsigned i = 0; i < 2; ++i)
2126 for (unsigned j = 0; j < 4; ++j)
2127 if (!isConstantOrUndef(N->getMaskElt(i*4+j),
2128 i*RHSStartValue+j+IndexOffset) ||
2129 !isConstantOrUndef(N->getMaskElt(i*4+j+8),
2130 i*RHSStartValue+j+IndexOffset+8))
2131 return false;
2132 return true;
2133}
2134
2135/**
2136 * Determine if the specified shuffle mask is suitable for the vmrgew or
2137 * vmrgow instructions.
2138 *
2139 * \param[in] N The shuffle vector SD Node to analyze
2140 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
2141 * \param[in] ShuffleKind Identify the type of merge:
2142 * - 0 = big-endian merge with two different inputs;
2143 * - 1 = either-endian merge with two identical inputs;
2144 * - 2 = little-endian merge with two different inputs (inputs are swapped for
2145 * little-endian merges).
2146 * \param[in] DAG The current SelectionDAG
2147 * \return true iff this shuffle mask
2148 */
2150 unsigned ShuffleKind, SelectionDAG &DAG) {
2151 if (DAG.getDataLayout().isLittleEndian()) {
2152 unsigned indexOffset = CheckEven ? 4 : 0;
2153 if (ShuffleKind == 1) // Unary
2154 return isVMerge(N, indexOffset, 0);
2155 else if (ShuffleKind == 2) // swapped
2156 return isVMerge(N, indexOffset, 16);
2157 else
2158 return false;
2159 }
2160 else {
2161 unsigned indexOffset = CheckEven ? 0 : 4;
2162 if (ShuffleKind == 1) // Unary
2163 return isVMerge(N, indexOffset, 0);
2164 else if (ShuffleKind == 0) // Normal
2165 return isVMerge(N, indexOffset, 16);
2166 else
2167 return false;
2168 }
2169 return false;
2170}
2171
2172/// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
2173/// amount, otherwise return -1.
2174/// The ShuffleKind distinguishes between big-endian operations with two
2175/// different inputs (0), either-endian operations with two identical inputs
2176/// (1), and little-endian operations with two different inputs (2). For the
2177/// latter, the input operands are swapped (see PPCInstrAltivec.td).
2178int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
2179 SelectionDAG &DAG) {
2180 if (N->getValueType(0) != MVT::v16i8)
2181 return -1;
2182
2183 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2184
2185 // Find the first non-undef value in the shuffle mask.
2186 unsigned i;
2187 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
2188 /*search*/;
2189
2190 if (i == 16) return -1; // all undef.
2191
2192 // Otherwise, check to see if the rest of the elements are consecutively
2193 // numbered from this value.
2194 unsigned ShiftAmt = SVOp->getMaskElt(i);
2195 if (ShiftAmt < i) return -1;
2196
2197 ShiftAmt -= i;
2198 bool isLE = DAG.getDataLayout().isLittleEndian();
2199
2200 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
2201 // Check the rest of the elements to see if they are consecutive.
2202 for (++i; i != 16; ++i)
2203 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2204 return -1;
2205 } else if (ShuffleKind == 1) {
2206 // Check the rest of the elements to see if they are consecutive.
2207 for (++i; i != 16; ++i)
2208 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
2209 return -1;
2210 } else
2211 return -1;
2212
2213 if (isLE)
2214 ShiftAmt = 16 - ShiftAmt;
2215
2216 return ShiftAmt;
2217}
2218
2219/// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
2220/// specifies a splat of a single element that is suitable for input to
2221/// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
2223 EVT VT = N->getValueType(0);
2224 if (VT == MVT::v2i64 || VT == MVT::v2f64)
2225 return EltSize == 8 && N->getMaskElt(0) == N->getMaskElt(1);
2226
2227 assert(VT == MVT::v16i8 && isPowerOf2_32(EltSize) &&
2228 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
2229
2230 // The consecutive indices need to specify an element, not part of two
2231 // different elements. So abandon ship early if this isn't the case.
2232 if (N->getMaskElt(0) % EltSize != 0)
2233 return false;
2234
2235 // This is a splat operation if each element of the permute is the same, and
2236 // if the value doesn't reference the second vector.
2237 unsigned ElementBase = N->getMaskElt(0);
2238
2239 // FIXME: Handle UNDEF elements too!
2240 if (ElementBase >= 16)
2241 return false;
2242
2243 // Check that the indices are consecutive, in the case of a multi-byte element
2244 // splatted with a v16i8 mask.
2245 for (unsigned i = 1; i != EltSize; ++i)
2246 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2247 return false;
2248
2249 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2250 if (N->getMaskElt(i) < 0) continue;
2251 for (unsigned j = 0; j != EltSize; ++j)
2252 if (N->getMaskElt(i+j) != N->getMaskElt(j))
2253 return false;
2254 }
2255 return true;
2256}
2257
2258/// Check that the mask is shuffling N byte elements. Within each N byte
2259/// element of the mask, the indices could be either in increasing or
2260/// decreasing order as long as they are consecutive.
2261/// \param[in] N the shuffle vector SD Node to analyze
2262/// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2263/// Word/DoubleWord/QuadWord).
2264/// \param[in] StepLen the delta indices number among the N byte element, if
2265/// the mask is in increasing/decreasing order then it is 1/-1.
2266/// \return true iff the mask is shuffling N byte elements.
2267static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
2268 int StepLen) {
2269 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
2270 "Unexpected element width.");
2271 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2272
2273 unsigned NumOfElem = 16 / Width;
2274 unsigned MaskVal[16]; // Width is never greater than 16
2275 for (unsigned i = 0; i < NumOfElem; ++i) {
2276 MaskVal[0] = N->getMaskElt(i * Width);
2277 if ((StepLen == 1) && (MaskVal[0] % Width)) {
2278 return false;
2279 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2280 return false;
2281 }
2282
2283 for (unsigned int j = 1; j < Width; ++j) {
2284 MaskVal[j] = N->getMaskElt(i * Width + j);
2285 if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2286 return false;
2287 }
2288 }
2289 }
2290
2291 return true;
2292}
2293
2294bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2295 unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2296 if (!isNByteElemShuffleMask(N, 4, 1))
2297 return false;
2298
2299 // Now we look at mask elements 0,4,8,12
2300 unsigned M0 = N->getMaskElt(0) / 4;
2301 unsigned M1 = N->getMaskElt(4) / 4;
2302 unsigned M2 = N->getMaskElt(8) / 4;
2303 unsigned M3 = N->getMaskElt(12) / 4;
2304 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2305 unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2306
2307 // Below, let H and L be arbitrary elements of the shuffle mask
2308 // where H is in the range [4,7] and L is in the range [0,3].
2309 // H, 1, 2, 3 or L, 5, 6, 7
2310 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2311 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2312 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2313 InsertAtByte = IsLE ? 12 : 0;
2314 Swap = M0 < 4;
2315 return true;
2316 }
2317 // 0, H, 2, 3 or 4, L, 6, 7
2318 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2319 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2320 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2321 InsertAtByte = IsLE ? 8 : 4;
2322 Swap = M1 < 4;
2323 return true;
2324 }
2325 // 0, 1, H, 3 or 4, 5, L, 7
2326 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2327 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2328 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2329 InsertAtByte = IsLE ? 4 : 8;
2330 Swap = M2 < 4;
2331 return true;
2332 }
2333 // 0, 1, 2, H or 4, 5, 6, L
2334 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2335 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2336 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2337 InsertAtByte = IsLE ? 0 : 12;
2338 Swap = M3 < 4;
2339 return true;
2340 }
2341
2342 // If both vector operands for the shuffle are the same vector, the mask will
2343 // contain only elements from the first one and the second one will be undef.
2344 if (N->getOperand(1).isUndef()) {
2345 ShiftElts = 0;
2346 Swap = true;
2347 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2348 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2349 InsertAtByte = IsLE ? 12 : 0;
2350 return true;
2351 }
2352 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2353 InsertAtByte = IsLE ? 8 : 4;
2354 return true;
2355 }
2356 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2357 InsertAtByte = IsLE ? 4 : 8;
2358 return true;
2359 }
2360 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2361 InsertAtByte = IsLE ? 0 : 12;
2362 return true;
2363 }
2364 }
2365
2366 return false;
2367}
2368
2370 bool &Swap, bool IsLE) {
2371 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2372 // Ensure each byte index of the word is consecutive.
2373 if (!isNByteElemShuffleMask(N, 4, 1))
2374 return false;
2375
2376 // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2377 unsigned M0 = N->getMaskElt(0) / 4;
2378 unsigned M1 = N->getMaskElt(4) / 4;
2379 unsigned M2 = N->getMaskElt(8) / 4;
2380 unsigned M3 = N->getMaskElt(12) / 4;
2381
2382 // If both vector operands for the shuffle are the same vector, the mask will
2383 // contain only elements from the first one and the second one will be undef.
2384 if (N->getOperand(1).isUndef()) {
2385 assert(M0 < 4 && "Indexing into an undef vector?");
2386 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2387 return false;
2388
2389 ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2390 Swap = false;
2391 return true;
2392 }
2393
2394 // Ensure each word index of the ShuffleVector Mask is consecutive.
2395 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2396 return false;
2397
2398 if (IsLE) {
2399 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2400 // Input vectors don't need to be swapped if the leading element
2401 // of the result is one of the 3 left elements of the second vector
2402 // (or if there is no shift to be done at all).
2403 Swap = false;
2404 ShiftElts = (8 - M0) % 8;
2405 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2406 // Input vectors need to be swapped if the leading element
2407 // of the result is one of the 3 left elements of the first vector
2408 // (or if we're shifting by 4 - thereby simply swapping the vectors).
2409 Swap = true;
2410 ShiftElts = (4 - M0) % 4;
2411 }
2412
2413 return true;
2414 } else { // BE
2415 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2416 // Input vectors don't need to be swapped if the leading element
2417 // of the result is one of the 4 elements of the first vector.
2418 Swap = false;
2419 ShiftElts = M0;
2420 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2421 // Input vectors need to be swapped if the leading element
2422 // of the result is one of the 4 elements of the right vector.
2423 Swap = true;
2424 ShiftElts = M0 - 4;
2425 }
2426
2427 return true;
2428 }
2429}
2430
2432 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2433
2434 if (!isNByteElemShuffleMask(N, Width, -1))
2435 return false;
2436
2437 for (int i = 0; i < 16; i += Width)
2438 if (N->getMaskElt(i) != i + Width - 1)
2439 return false;
2440
2441 return true;
2442}
2443
2445 return isXXBRShuffleMaskHelper(N, 2);
2446}
2447
2449 return isXXBRShuffleMaskHelper(N, 4);
2450}
2451
2453 return isXXBRShuffleMaskHelper(N, 8);
2454}
2455
2457 return isXXBRShuffleMaskHelper(N, 16);
2458}
2459
2460/// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2461/// if the inputs to the instruction should be swapped and set \p DM to the
2462/// value for the immediate.
2463/// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2464/// AND element 0 of the result comes from the first input (LE) or second input
2465/// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2466/// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2467/// mask.
2469 bool &Swap, bool IsLE) {
2470 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2471
2472 // Ensure each byte index of the double word is consecutive.
2473 if (!isNByteElemShuffleMask(N, 8, 1))
2474 return false;
2475
2476 unsigned M0 = N->getMaskElt(0) / 8;
2477 unsigned M1 = N->getMaskElt(8) / 8;
2478 assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2479
2480 // If both vector operands for the shuffle are the same vector, the mask will
2481 // contain only elements from the first one and the second one will be undef.
2482 if (N->getOperand(1).isUndef()) {
2483 if ((M0 | M1) < 2) {
2484 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2485 Swap = false;
2486 return true;
2487 } else
2488 return false;
2489 }
2490
2491 if (IsLE) {
2492 if (M0 > 1 && M1 < 2) {
2493 Swap = false;
2494 } else if (M0 < 2 && M1 > 1) {
2495 M0 = (M0 + 2) % 4;
2496 M1 = (M1 + 2) % 4;
2497 Swap = true;
2498 } else
2499 return false;
2500
2501 // Note: if control flow comes here that means Swap is already set above
2502 DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2503 return true;
2504 } else { // BE
2505 if (M0 < 2 && M1 > 1) {
2506 Swap = false;
2507 } else if (M0 > 1 && M1 < 2) {
2508 M0 = (M0 + 2) % 4;
2509 M1 = (M1 + 2) % 4;
2510 Swap = true;
2511 } else
2512 return false;
2513
2514 // Note: if control flow comes here that means Swap is already set above
2515 DM = (M0 << 1) + (M1 & 1);
2516 return true;
2517 }
2518}
2519
2520
2521/// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2522/// appropriate for PPC mnemonics (which have a big endian bias - namely
2523/// elements are counted from the left of the vector register).
2524unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2525 SelectionDAG &DAG) {
2526 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2527 assert(isSplatShuffleMask(SVOp, EltSize));
2528 EVT VT = SVOp->getValueType(0);
2529
2530 if (VT == MVT::v2i64 || VT == MVT::v2f64)
2531 return DAG.getDataLayout().isLittleEndian() ? 1 - SVOp->getMaskElt(0)
2532 : SVOp->getMaskElt(0);
2533
2534 if (DAG.getDataLayout().isLittleEndian())
2535 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2536 else
2537 return SVOp->getMaskElt(0) / EltSize;
2538}
2539
2540/// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2541/// by using a vspltis[bhw] instruction of the specified element size, return
2542/// the constant being splatted. The ByteSize field indicates the number of
2543/// bytes of each element [124] -> [bhw].
2545 SDValue OpVal;
2546
2547 // If ByteSize of the splat is bigger than the element size of the
2548 // build_vector, then we have a case where we are checking for a splat where
2549 // multiple elements of the buildvector are folded together into a single
2550 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2551 unsigned EltSize = 16/N->getNumOperands();
2552 if (EltSize < ByteSize) {
2553 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
2554 SDValue UniquedVals[4];
2555 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2556
2557 // See if all of the elements in the buildvector agree across.
2558 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2559 if (N->getOperand(i).isUndef()) continue;
2560 // If the element isn't a constant, bail fully out.
2561 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2562
2563 if (!UniquedVals[i&(Multiple-1)].getNode())
2564 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2565 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2566 return SDValue(); // no match.
2567 }
2568
2569 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2570 // either constant or undef values that are identical for each chunk. See
2571 // if these chunks can form into a larger vspltis*.
2572
2573 // Check to see if all of the leading entries are either 0 or -1. If
2574 // neither, then this won't fit into the immediate field.
2575 bool LeadingZero = true;
2576 bool LeadingOnes = true;
2577 for (unsigned i = 0; i != Multiple-1; ++i) {
2578 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
2579
2580 LeadingZero &= isNullConstant(UniquedVals[i]);
2581 LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2582 }
2583 // Finally, check the least significant entry.
2584 if (LeadingZero) {
2585 if (!UniquedVals[Multiple-1].getNode())
2586 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
2587 int Val = UniquedVals[Multiple - 1]->getAsZExtVal();
2588 if (Val < 16) // 0,0,0,4 -> vspltisw(4)
2589 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2590 }
2591 if (LeadingOnes) {
2592 if (!UniquedVals[Multiple-1].getNode())
2593 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2594 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2595 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
2596 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2597 }
2598
2599 return SDValue();
2600 }
2601
2602 // Check to see if this buildvec has a single non-undef value in its elements.
2603 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2604 if (N->getOperand(i).isUndef()) continue;
2605 if (!OpVal.getNode())
2606 OpVal = N->getOperand(i);
2607 else if (OpVal != N->getOperand(i))
2608 return SDValue();
2609 }
2610
2611 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
2612
2613 unsigned ValSizeInBytes = EltSize;
2614 uint64_t Value = 0;
2615 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2616 Value = CN->getZExtValue();
2617 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2618 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2619 Value = llvm::bit_cast<uint32_t>(CN->getValueAPF().convertToFloat());
2620 }
2621
2622 // If the splat value is larger than the element value, then we can never do
2623 // this splat. The only case that we could fit the replicated bits into our
2624 // immediate field for would be zero, and we prefer to use vxor for it.
2625 if (ValSizeInBytes < ByteSize) return SDValue();
2626
2627 // If the element value is larger than the splat value, check if it consists
2628 // of a repeated bit pattern of size ByteSize.
2629 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2630 return SDValue();
2631
2632 // Properly sign extend the value.
2633 int MaskVal = SignExtend32(Value, ByteSize * 8);
2634
2635 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2636 if (MaskVal == 0) return SDValue();
2637
2638 // Finally, if this value fits in a 5 bit sext field, return it
2639 if (SignExtend32<5>(MaskVal) == MaskVal)
2640 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2641 return SDValue();
2642}
2643
2644//===----------------------------------------------------------------------===//
2645// Addressing Mode Selection
2646//===----------------------------------------------------------------------===//
2647
2648/// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2649/// or 64-bit immediate, and if the value can be accurately represented as a
2650/// sign extension from a 16-bit value. If so, this returns true and the
2651/// immediate.
2652bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2653 if (!isa<ConstantSDNode>(N))
2654 return false;
2655
2656 Imm = (int16_t)N->getAsZExtVal();
2657 if (N->getValueType(0) == MVT::i32)
2658 return Imm == (int32_t)N->getAsZExtVal();
2659 else
2660 return Imm == (int64_t)N->getAsZExtVal();
2661}
2663 return isIntS16Immediate(Op.getNode(), Imm);
2664}
2665
2666/// Used when computing address flags for selecting loads and stores.
2667/// If we have an OR, check if the LHS and RHS are provably disjoint.
2668/// An OR of two provably disjoint values is equivalent to an ADD.
2669/// Most PPC load/store instructions compute the effective address as a sum,
2670/// so doing this conversion is useful.
2671static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) {
2672 if (N.getOpcode() != ISD::OR)
2673 return false;
2674 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2675 if (!LHSKnown.Zero.getBoolValue())
2676 return false;
2677 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2678 return (~(LHSKnown.Zero | RHSKnown.Zero) == 0);
2679}
2680
2681/// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2682/// be represented as an indexed [r+r] operation.
2684 SDValue &Index,
2685 SelectionDAG &DAG) const {
2686 for (SDNode *U : N->uses()) {
2687 if (MemSDNode *Memop = dyn_cast<MemSDNode>(U)) {
2688 if (Memop->getMemoryVT() == MVT::f64) {
2689 Base = N.getOperand(0);
2690 Index = N.getOperand(1);
2691 return true;
2692 }
2693 }
2694 }
2695 return false;
2696}
2697
2698/// isIntS34Immediate - This method tests if value of node given can be
2699/// accurately represented as a sign extension from a 34-bit value. If so,
2700/// this returns true and the immediate.
2701bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2702 if (!isa<ConstantSDNode>(N))
2703 return false;
2704
2705 Imm = (int64_t)N->getAsZExtVal();
2706 return isInt<34>(Imm);
2707}
2709 return isIntS34Immediate(Op.getNode(), Imm);
2710}
2711
2712/// SelectAddressRegReg - Given the specified addressed, check to see if it
2713/// can be represented as an indexed [r+r] operation. Returns false if it
2714/// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2715/// non-zero and N can be represented by a base register plus a signed 16-bit
2716/// displacement, make a more precise judgement by checking (displacement % \p
2717/// EncodingAlignment).
2720 MaybeAlign EncodingAlignment) const {
2721 // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2722 // a [pc+imm].
2724 return false;
2725
2726 int16_t Imm = 0;
2727 if (N.getOpcode() == ISD::ADD) {
2728 // Is there any SPE load/store (f64), which can't handle 16bit offset?
2729 // SPE load/store can only handle 8-bit offsets.
2730 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2731 return true;
2732 if (isIntS16Immediate(N.getOperand(1), Imm) &&
2733 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2734 return false; // r+i
2735 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2736 return false; // r+i
2737
2738 Base = N.getOperand(0);
2739 Index = N.getOperand(1);
2740 return true;
2741 } else if (N.getOpcode() == ISD::OR) {
2742 if (isIntS16Immediate(N.getOperand(1), Imm) &&
2743 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2744 return false; // r+i can fold it if we can.
2745
2746 // If this is an or of disjoint bitfields, we can codegen this as an add
2747 // (for better address arithmetic) if the LHS and RHS of the OR are provably
2748 // disjoint.
2749 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2750
2751 if (LHSKnown.Zero.getBoolValue()) {
2752 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2753 // If all of the bits are known zero on the LHS or RHS, the add won't
2754 // carry.
2755 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2756 Base = N.getOperand(0);
2757 Index = N.getOperand(1);
2758 return true;
2759 }
2760 }
2761 }
2762
2763 return false;
2764}
2765
2766// If we happen to be doing an i64 load or store into a stack slot that has
2767// less than a 4-byte alignment, then the frame-index elimination may need to
2768// use an indexed load or store instruction (because the offset may not be a
2769// multiple of 4). The extra register needed to hold the offset comes from the
2770// register scavenger, and it is possible that the scavenger will need to use
2771// an emergency spill slot. As a result, we need to make sure that a spill slot
2772// is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2773// stack slot.
2774static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2775 // FIXME: This does not handle the LWA case.
2776 if (VT != MVT::i64)
2777 return;
2778
2779 // NOTE: We'll exclude negative FIs here, which come from argument
2780 // lowering, because there are no known test cases triggering this problem
2781 // using packed structures (or similar). We can remove this exclusion if
2782 // we find such a test case. The reason why this is so test-case driven is
2783 // because this entire 'fixup' is only to prevent crashes (from the
2784 // register scavenger) on not-really-valid inputs. For example, if we have:
2785 // %a = alloca i1
2786 // %b = bitcast i1* %a to i64*
2787 // store i64* a, i64 b
2788 // then the store should really be marked as 'align 1', but is not. If it
2789 // were marked as 'align 1' then the indexed form would have been
2790 // instruction-selected initially, and the problem this 'fixup' is preventing
2791 // won't happen regardless.
2792 if (FrameIdx < 0)
2793 return;
2794
2796 MachineFrameInfo &MFI = MF.getFrameInfo();
2797
2798 if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2799 return;
2800
2801 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2802 FuncInfo->setHasNonRISpills();
2803}
2804
2805/// Returns true if the address N can be represented by a base register plus
2806/// a signed 16-bit displacement [r+imm], and if it is not better
2807/// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept
2808/// displacements that are multiples of that value.
2810 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2811 MaybeAlign EncodingAlignment) const {
2812 // FIXME dl should come from parent load or store, not from address
2813 SDLoc dl(N);
2814
2815 // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2816 // a [pc+imm].
2818 return false;
2819
2820 // If this can be more profitably realized as r+r, fail.
2821 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2822 return false;
2823
2824 if (N.getOpcode() == ISD::ADD) {
2825 int16_t imm = 0;
2826 if (isIntS16Immediate(N.getOperand(1), imm) &&
2827 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2828 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2829 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2830 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2831 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2832 } else {
2833 Base = N.getOperand(0);
2834 }
2835 return true; // [r+i]
2836 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2837 // Match LOAD (ADD (X, Lo(G))).
2838 assert(!N.getOperand(1).getConstantOperandVal(1) &&
2839 "Cannot handle constant offsets yet!");
2840 Disp = N.getOperand(1).getOperand(0); // The global address.
2845 Base = N.getOperand(0);
2846 return true; // [&g+r]
2847 }
2848 } else if (N.getOpcode() == ISD::OR) {
2849 int16_t imm = 0;
2850 if (isIntS16Immediate(N.getOperand(1), imm) &&
2851 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2852 // If this is an or of disjoint bitfields, we can codegen this as an add
2853 // (for better address arithmetic) if the LHS and RHS of the OR are
2854 // provably disjoint.
2855 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2856
2857 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2858 // If all of the bits are known zero on the LHS or RHS, the add won't
2859 // carry.
2860 if (FrameIndexSDNode *FI =
2861 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2862 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2863 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2864 } else {
2865 Base = N.getOperand(0);
2866 }
2867 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2868 return true;
2869 }
2870 }
2871 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2872 // Loading from a constant address.
2873
2874 // If this address fits entirely in a 16-bit sext immediate field, codegen
2875 // this as "d, 0"
2876 int16_t Imm;
2877 if (isIntS16Immediate(CN, Imm) &&
2878 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2879 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2880 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2881 CN->getValueType(0));
2882 return true;
2883 }
2884
2885 // Handle 32-bit sext immediates with LIS + addr mode.
2886 if ((CN->getValueType(0) == MVT::i32 ||
2887 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2888 (!EncodingAlignment ||
2889 isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2890 int Addr = (int)CN->getZExtValue();
2891
2892 // Otherwise, break this down into an LIS + disp.
2893 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2894
2895 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2896 MVT::i32);
2897 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2898 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2899 return true;
2900 }
2901 }
2902
2903 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2904 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2905 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2906 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2907 } else
2908 Base = N;
2909 return true; // [r+0]
2910}
2911
2912/// Similar to the 16-bit case but for instructions that take a 34-bit
2913/// displacement field (prefixed loads/stores).
2915 SDValue &Base,
2916 SelectionDAG &DAG) const {
2917 // Only on 64-bit targets.
2918 if (N.getValueType() != MVT::i64)
2919 return false;
2920
2921 SDLoc dl(N);
2922 int64_t Imm = 0;
2923
2924 if (N.getOpcode() == ISD::ADD) {
2925 if (!isIntS34Immediate(N.getOperand(1), Imm))
2926 return false;
2927 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2928 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2929 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2930 else
2931 Base = N.getOperand(0);
2932 return true;
2933 }
2934
2935 if (N.getOpcode() == ISD::OR) {
2936 if (!isIntS34Immediate(N.getOperand(1), Imm))
2937 return false;
2938 // If this is an or of disjoint bitfields, we can codegen this as an add
2939 // (for better address arithmetic) if the LHS and RHS of the OR are
2940 // provably disjoint.
2941 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2942 if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2943 return false;
2944 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2945 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2946 else
2947 Base = N.getOperand(0);
2948 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2949 return true;
2950 }
2951
2952 if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2953 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2954 Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2955 return true;
2956 }
2957
2958 return false;
2959}
2960
2961/// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2962/// represented as an indexed [r+r] operation.
2964 SDValue &Index,
2965 SelectionDAG &DAG) const {
2966 // Check to see if we can easily represent this as an [r+r] address. This
2967 // will fail if it thinks that the address is more profitably represented as
2968 // reg+imm, e.g. where imm = 0.
2969 if (SelectAddressRegReg(N, Base, Index, DAG))
2970 return true;
2971
2972 // If the address is the result of an add, we will utilize the fact that the
2973 // address calculation includes an implicit add. However, we can reduce
2974 // register pressure if we do not materialize a constant just for use as the
2975 // index register. We only get rid of the add if it is not an add of a
2976 // value and a 16-bit signed constant and both have a single use.
2977 int16_t imm = 0;
2978 if (N.getOpcode() == ISD::ADD &&
2979 (!isIntS16Immediate(N.getOperand(1), imm) ||
2980 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2981 Base = N.getOperand(0);
2982 Index = N.getOperand(1);
2983 return true;
2984 }
2985
2986 // Otherwise, do it the hard way, using R0 as the base register.
2987 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2988 N.getValueType());
2989 Index = N;
2990 return true;
2991}
2992
2993template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2994 Ty *PCRelCand = dyn_cast<Ty>(N);
2995 return PCRelCand && (PPCInstrInfo::hasPCRelFlag(PCRelCand->getTargetFlags()));
2996}
2997
2998/// Returns true if this address is a PC Relative address.
2999/// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
3000/// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
3002 // This is a materialize PC Relative node. Always select this as PC Relative.
3003 Base = N;
3004 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
3005 return true;
3006 if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
3007 isValidPCRelNode<GlobalAddressSDNode>(N) ||
3008 isValidPCRelNode<JumpTableSDNode>(N) ||
3009 isValidPCRelNode<BlockAddressSDNode>(N))
3010 return true;
3011 return false;
3012}
3013
3014/// Returns true if we should use a direct load into vector instruction
3015/// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
3016static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
3017
3018 // If there are any other uses other than scalar to vector, then we should
3019 // keep it as a scalar load -> direct move pattern to prevent multiple
3020 // loads.
3021 LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
3022 if (!LD)
3023 return false;
3024
3025 EVT MemVT = LD->getMemoryVT();
3026 if (!MemVT.isSimple())
3027 return false;
3028 switch(MemVT.getSimpleVT().SimpleTy) {
3029 case MVT::i64:
3030 break;
3031 case MVT::i32:
3032 if (!ST.hasP8Vector())
3033 return false;
3034 break;
3035 case MVT::i16:
3036 case MVT::i8:
3037 if (!ST.hasP9Vector())
3038 return false;
3039 break;
3040 default:
3041 return false;
3042 }
3043
3044 SDValue LoadedVal(N, 0);
3045 if (!LoadedVal.hasOneUse())
3046 return false;
3047
3048 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
3049 UI != UE; ++UI)
3050 if (UI.getUse().get().getResNo() == 0 &&
3051 UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
3052 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
3053 return false;
3054
3055 return true;
3056}
3057
3058/// getPreIndexedAddressParts - returns true by value, base pointer and
3059/// offset pointer and addressing mode by reference if the node's address
3060/// can be legally represented as pre-indexed load / store address.
3062 SDValue &Offset,
3064 SelectionDAG &DAG) const {
3065 if (DisablePPCPreinc) return false;
3066
3067 bool isLoad = true;
3068 SDValue Ptr;
3069 EVT VT;
3070 Align Alignment;
3071 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3072 Ptr = LD->getBasePtr();
3073 VT = LD->getMemoryVT();
3074 Alignment = LD->getAlign();
3075 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3076 Ptr = ST->getBasePtr();
3077 VT = ST->getMemoryVT();
3078 Alignment = ST->getAlign();
3079 isLoad = false;
3080 } else
3081 return false;
3082
3083 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
3084 // instructions because we can fold these into a more efficient instruction
3085 // instead, (such as LXSD).
3086 if (isLoad && usePartialVectorLoads(N, Subtarget)) {
3087 return false;
3088 }
3089
3090 // PowerPC doesn't have preinc load/store instructions for vectors
3091 if (VT.isVector())
3092 return false;
3093
3094 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
3095 // Common code will reject creating a pre-inc form if the base pointer
3096 // is a frame index, or if N is a store and the base pointer is either
3097 // the same as or a predecessor of the value being stored. Check for
3098 // those situations here, and try with swapped Base/Offset instead.
3099 bool Swap = false;
3100
3101 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
3102 Swap = true;
3103 else if (!isLoad) {
3104 SDValue Val = cast<StoreSDNode>(N)->getValue();
3105 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
3106 Swap = true;
3107 }
3108
3109 if (Swap)
3111
3112 AM = ISD::PRE_INC;
3113 return true;
3114 }
3115
3116 // LDU/STU can only handle immediates that are a multiple of 4.
3117 if (VT != MVT::i64) {
3118 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, std::nullopt))
3119 return false;
3120 } else {
3121 // LDU/STU need an address with at least 4-byte alignment.
3122 if (Alignment < Align(4))
3123 return false;
3124
3125 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
3126 return false;
3127 }
3128
3129 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3130 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
3131 // sext i32 to i64 when addr mode is r+i.
3132 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
3133 LD->getExtensionType() == ISD::SEXTLOAD &&
3134 isa<ConstantSDNode>(Offset))
3135 return false;
3136 }
3137
3138 AM = ISD::PRE_INC;
3139 return true;
3140}
3141
3142//===----------------------------------------------------------------------===//
3143// LowerOperation implementation
3144//===----------------------------------------------------------------------===//
3145
3146/// Return true if we should reference labels using a PICBase, set the HiOpFlags
3147/// and LoOpFlags to the target MO flags.
3148static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
3149 unsigned &HiOpFlags, unsigned &LoOpFlags,
3150 const GlobalValue *GV = nullptr) {
3151 HiOpFlags = PPCII::MO_HA;
3152 LoOpFlags = PPCII::MO_LO;
3153
3154 // Don't use the pic base if not in PIC relocation model.
3155 if (IsPIC) {
3156 HiOpFlags = PPCII::MO_PIC_HA_FLAG;
3157 LoOpFlags = PPCII::MO_PIC_LO_FLAG;
3158 }
3159}
3160
3161static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
3162 SelectionDAG &DAG) {
3163 SDLoc DL(HiPart);
3164 EVT PtrVT = HiPart.getValueType();
3165 SDValue Zero = DAG.getConstant(0, DL, PtrVT);
3166
3167 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
3168 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
3169
3170 // With PIC, the first instruction is actually "GR+hi(&G)".
3171 if (isPIC)
3172 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
3173 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
3174
3175 // Generate non-pic code that has direct accesses to the constant pool.
3176 // The address of the global is just (hi(&g)+lo(&g)).
3177 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
3178}
3179
3181 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3182 FuncInfo->setUsesTOCBasePtr();
3183}
3184
3187}
3188
3189SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
3190 SDValue GA) const {
3191 const bool Is64Bit = Subtarget.isPPC64();
3192 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
3193 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
3194 : Subtarget.isAIXABI()
3195 ? DAG.getRegister(PPC::R2, VT)
3196 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
3197 SDValue Ops[] = { GA, Reg };
3198 return DAG.getMemIntrinsicNode(
3199 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
3202}
3203
3204SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
3205 SelectionDAG &DAG) const {
3206 EVT PtrVT = Op.getValueType();
3207 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3208 const Constant *C = CP->getConstVal();
3209
3210 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3211 // The actual address of the GlobalValue is stored in the TOC.
3212 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3213 if (Subtarget.isUsingPCRelativeCalls()) {
3214 SDLoc DL(CP);
3215 EVT Ty = getPointerTy(DAG.getDataLayout());
3216 SDValue ConstPool = DAG.getTargetConstantPool(
3217 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
3218 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
3219 }
3220 setUsesTOCBasePtr(DAG);
3221 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
3222 return getTOCEntry(DAG, SDLoc(CP), GA);
3223 }
3224
3225 unsigned MOHiFlag, MOLoFlag;
3226 bool IsPIC = isPositionIndependent();
3227 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3228
3229 if (IsPIC && Subtarget.isSVR4ABI()) {
3230 SDValue GA =
3231 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
3232 return getTOCEntry(DAG, SDLoc(CP), GA);
3233 }
3234
3235 SDValue CPIHi =
3236 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
3237 SDValue CPILo =
3238 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
3239 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
3240}
3241
3242// For 64-bit PowerPC, prefer the more compact relative encodings.
3243// This trades 32 bits per jump table entry for one or two instructions
3244// on the jump site.
3246 if (isJumpTableRelative())
3248
3250}
3251
3254 return false;
3255 if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3256 return true;
3258}
3259
3261 SelectionDAG &DAG) const {
3262 if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3264
3265 switch (getTargetMachine().getCodeModel()) {
3266 case CodeModel::Small:
3267 case CodeModel::Medium:
3269 default:
3270 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3272 }
3273}
3274
3275const MCExpr *
3277 unsigned JTI,
3278 MCContext &Ctx) const {
3279 if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3281
3282 switch (getTargetMachine().getCodeModel()) {
3283 case CodeModel::Small:
3284 case CodeModel::Medium:
3286 default:
3287 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3288 }
3289}
3290
3291SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3292 EVT PtrVT = Op.getValueType();
3293 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3294
3295 // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3296 if (Subtarget.isUsingPCRelativeCalls()) {
3297 SDLoc DL(JT);
3298 EVT Ty = getPointerTy(DAG.getDataLayout());
3299 SDValue GA =
3300 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
3301 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3302 return MatAddr;
3303 }
3304
3305 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3306 // The actual address of the GlobalValue is stored in the TOC.
3307 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3308 setUsesTOCBasePtr(DAG);
3309 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3310 return getTOCEntry(DAG, SDLoc(JT), GA);
3311 }
3312
3313 unsigned MOHiFlag, MOLoFlag;
3314 bool IsPIC = isPositionIndependent();
3315 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3316
3317 if (IsPIC && Subtarget.isSVR4ABI()) {
3318 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3320 return getTOCEntry(DAG, SDLoc(GA), GA);
3321 }
3322
3323 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3324 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3325 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3326}
3327
3328SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3329 SelectionDAG &DAG) const {
3330 EVT PtrVT = Op.getValueType();
3331 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3332 const BlockAddress *BA = BASDN->getBlockAddress();
3333
3334 // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3335 if (Subtarget.isUsingPCRelativeCalls()) {
3336 SDLoc DL(BASDN);
3337 EVT Ty = getPointerTy(DAG.getDataLayout());
3338 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3340 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3341 return MatAddr;
3342 }
3343
3344 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3345 // The actual BlockAddress is stored in the TOC.
3346 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3347 setUsesTOCBasePtr(DAG);
3348 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3349 return getTOCEntry(DAG, SDLoc(BASDN), GA);
3350 }
3351
3352 // 32-bit position-independent ELF stores the BlockAddress in the .got.
3353 if (Subtarget.is32BitELFABI() && isPositionIndependent())
3354 return getTOCEntry(
3355 DAG, SDLoc(BASDN),
3356 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3357
3358 unsigned MOHiFlag, MOLoFlag;
3359 bool IsPIC = isPositionIndependent();
3360 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3361 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3362 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3363 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3364}
3365
3366SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3367 SelectionDAG &DAG) const {
3368 if (Subtarget.isAIXABI())
3369 return LowerGlobalTLSAddressAIX(Op, DAG);
3370
3371 return LowerGlobalTLSAddressLinux(Op, DAG);
3372}
3373
3374/// updateForAIXShLibTLSModelOpt - Helper to initialize TLS model opt settings,
3375/// and then apply the update.
3377 SelectionDAG &DAG,
3378 const TargetMachine &TM) {
3379 // Initialize TLS model opt setting lazily:
3380 // (1) Use initial-exec for single TLS var references within current function.
3381 // (2) Use local-dynamic for multiple TLS var references within current
3382 // function.
3383 PPCFunctionInfo *FuncInfo =
3385 if (!FuncInfo->isAIXFuncTLSModelOptInitDone()) {
3387 // Iterate over all instructions within current function, collect all TLS
3388 // global variables (global variables taken as the first parameter to
3389 // Intrinsic::threadlocal_address).
3390 const Function &Func = DAG.getMachineFunction().getFunction();
3391 for (const BasicBlock &BB : Func)
3392 for (const Instruction &I : BB)
3393 if (I.getOpcode() == Instruction::Call)
3394 if (const CallInst *CI = dyn_cast<const CallInst>(&I))
3395 if (Function *CF = CI->getCalledFunction())
3396 if (CF->isDeclaration() &&
3397 CF->getIntrinsicID() == Intrinsic::threadlocal_address)
3398 if (const GlobalValue *GV =
3399 dyn_cast<GlobalValue>(I.getOperand(0))) {
3400 TLSModel::Model GVModel = TM.getTLSModel(GV);
3401 if (GVModel == TLSModel::LocalDynamic)
3402 TLSGV.insert(GV);
3403 }
3404
3405 unsigned TLSGVCnt = TLSGV.size();
3406 LLVM_DEBUG(dbgs() << format("LocalDynamic TLSGV count:%d\n", TLSGVCnt));
3407 if (TLSGVCnt <= PPCAIXTLSModelOptUseIEForLDLimit)
3408 FuncInfo->setAIXFuncUseTLSIEForLD();
3410 }
3411
3412 if (FuncInfo->isAIXFuncUseTLSIEForLD()) {
3413 LLVM_DEBUG(
3414 dbgs() << DAG.getMachineFunction().getName()
3415 << " function is using the TLS-IE model for TLS-LD access.\n");
3416 Model = TLSModel::InitialExec;
3417 }
3418}
3419
3420SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
3421 SelectionDAG &DAG) const {
3422 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3423
3424 if (DAG.getTarget().useEmulatedTLS())
3425 report_fatal_error("Emulated TLS is not yet supported on AIX");
3426
3427 SDLoc dl(GA);
3428 const GlobalValue *GV = GA->getGlobal();
3429 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3430 bool Is64Bit = Subtarget.isPPC64();
3432
3433 // Apply update to the TLS model.
3434 if (Subtarget.hasAIXShLibTLSModelOpt())
3436
3437 bool IsTLSLocalExecModel = Model == TLSModel::LocalExec;
3438
3439 if (IsTLSLocalExecModel || Model == TLSModel::InitialExec) {
3440 bool HasAIXSmallLocalExecTLS = Subtarget.hasAIXSmallLocalExecTLS();
3441 bool HasAIXSmallTLSGlobalAttr = false;
3442 SDValue VariableOffsetTGA =
3443 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TPREL_FLAG);
3444 SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3445 SDValue TLSReg;
3446
3447 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
3448 if (GVar->hasAttribute("aix-small-tls"))
3449 HasAIXSmallTLSGlobalAttr = true;
3450
3451 if (Is64Bit) {
3452 // For local-exec and initial-exec on AIX (64-bit), the sequence generated
3453 // involves a load of the variable offset (from the TOC), followed by an
3454 // add of the loaded variable offset to R13 (the thread pointer).
3455 // This code sequence looks like:
3456 // ld reg1,var[TC](2)
3457 // add reg2, reg1, r13 // r13 contains the thread pointer
3458 TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3459
3460 // With the -maix-small-local-exec-tls option, or with the "aix-small-tls"
3461 // global variable attribute, produce a faster access sequence for
3462 // local-exec TLS variables where the offset from the TLS base is encoded
3463 // as an immediate operand.
3464 //
3465 // We only utilize the faster local-exec access sequence when the TLS
3466 // variable has a size within the policy limit. We treat types that are
3467 // not sized or are empty as being over the policy size limit.
3468 if ((HasAIXSmallLocalExecTLS || HasAIXSmallTLSGlobalAttr) &&
3469 IsTLSLocalExecModel) {
3470 Type *GVType = GV->getValueType();
3471 if (GVType->isSized() && !GVType->isEmptyTy() &&
3472 GV->getDataLayout().getTypeAllocSize(GVType) <=
3474 return DAG.getNode(PPCISD::Lo, dl, PtrVT, VariableOffsetTGA, TLSReg);
3475 }
3476 } else {
3477 // For local-exec and initial-exec on AIX (32-bit), the sequence generated
3478 // involves loading the variable offset from the TOC, generating a call to
3479 // .__get_tpointer to get the thread pointer (which will be in R3), and
3480 // adding the two together:
3481 // lwz reg1,var[TC](2)
3482 // bla .__get_tpointer
3483 // add reg2, reg1, r3
3484 TLSReg = DAG.getNode(PPCISD::GET_TPOINTER, dl, PtrVT);
3485
3486 // We do not implement the 32-bit version of the faster access sequence
3487 // for local-exec that is controlled by the -maix-small-local-exec-tls
3488 // option, or the "aix-small-tls" global variable attribute.
3489 if (HasAIXSmallLocalExecTLS || HasAIXSmallTLSGlobalAttr)
3490 report_fatal_error("The small-local-exec TLS access sequence is "
3491 "currently only supported on AIX (64-bit mode).");
3492 }
3493 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, VariableOffset);
3494 }
3495
3496 if (Model == TLSModel::LocalDynamic) {
3497 bool HasAIXSmallLocalDynamicTLS = Subtarget.hasAIXSmallLocalDynamicTLS();
3498
3499 // We do not implement the 32-bit version of the faster access sequence
3500 // for local-dynamic that is controlled by -maix-small-local-dynamic-tls.
3501 if (!Is64Bit && HasAIXSmallLocalDynamicTLS)
3502 report_fatal_error("The small-local-dynamic TLS access sequence is "
3503 "currently only supported on AIX (64-bit mode).");
3504
3505 // For local-dynamic on AIX, we need to generate one TOC entry for each
3506 // variable offset, and a single module-handle TOC entry for the entire
3507 // file.
3508
3509 SDValue VariableOffsetTGA =
3510 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSLD_FLAG);
3511 SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3512
3514 GlobalVariable *TLSGV =
3515 dyn_cast_or_null<GlobalVariable>(M->getOrInsertGlobal(
3516 StringRef("_$TLSML"), PointerType::getUnqual(*DAG.getContext())));
3518 assert(TLSGV && "Not able to create GV for _$TLSML.");
3519 SDValue ModuleHandleTGA =
3520 DAG.getTargetGlobalAddress(TLSGV, dl, PtrVT, 0, PPCII::MO_TLSLDM_FLAG);
3521 SDValue ModuleHandleTOC = getTOCEntry(DAG, dl, ModuleHandleTGA);
3522 SDValue ModuleHandle =
3523 DAG.getNode(PPCISD::TLSLD_AIX, dl, PtrVT, ModuleHandleTOC);
3524
3525 // With the -maix-small-local-dynamic-tls option, produce a faster access
3526 // sequence for local-dynamic TLS variables where the offset from the
3527 // module-handle is encoded as an immediate operand.
3528 //
3529 // We only utilize the faster local-dynamic access sequence when the TLS
3530 // variable has a size within the policy limit. We treat types that are
3531 // not sized or are empty as being over the policy size limit.
3532 if (HasAIXSmallLocalDynamicTLS) {
3533 Type *GVType = GV->getValueType();
3534 if (GVType->isSized() && !GVType->isEmptyTy() &&
3535 GV->getDataLayout().getTypeAllocSize(GVType) <=
3537 return DAG.getNode(PPCISD::Lo, dl, PtrVT, VariableOffsetTGA,
3538 ModuleHandle);
3539 }
3540
3541 return DAG.getNode(ISD::ADD, dl, PtrVT, ModuleHandle, VariableOffset);
3542 }
3543
3544 // If Local- or Initial-exec or Local-dynamic is not possible or specified,
3545 // all GlobalTLSAddress nodes are lowered using the general-dynamic model. We
3546 // need to generate two TOC entries, one for the variable offset, one for the
3547 // region handle. The global address for the TOC entry of the region handle is
3548 // created with the MO_TLSGDM_FLAG flag and the global address for the TOC
3549 // entry of the variable offset is created with MO_TLSGD_FLAG.
3550 SDValue VariableOffsetTGA =
3551 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG);
3552 SDValue RegionHandleTGA =
3553 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG);
3554 SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3555 SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA);
3556 return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset,
3557 RegionHandle);
3558}
3559
3560SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op,
3561 SelectionDAG &DAG) const {
3562 // FIXME: TLS addresses currently use medium model code sequences,
3563 // which is the most useful form. Eventually support for small and
3564 // large models could be added if users need it, at the cost of
3565 // additional complexity.
3566 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3567 if (DAG.getTarget().useEmulatedTLS())
3568 return LowerToTLSEmulatedModel(GA, DAG);
3569
3570 SDLoc dl(GA);
3571 const GlobalValue *GV = GA->getGlobal();
3572 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3573 bool is64bit = Subtarget.isPPC64();
3574 const Module *M = DAG.getMachineFunction().getFunction().getParent();
3575 PICLevel::Level picLevel = M->getPICLevel();
3576
3578 TLSModel::Model Model = TM.getTLSModel(GV);
3579
3580 if (Model == TLSModel::LocalExec) {
3581 if (Subtarget.isUsingPCRelativeCalls()) {
3582 SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3583 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3585 SDValue MatAddr =
3586 DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3587 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3588 }
3589
3590 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3592 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3594 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3595 : DAG.getRegister(PPC::R2, MVT::i32);
3596
3597 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3598 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3599 }
3600
3601 if (Model == TLSModel::InitialExec) {
3602 bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3604 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3605 SDValue TGATLS = DAG.getTargetGlobalAddress(
3606 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_TLS_PCREL_FLAG : PPCII::MO_TLS);
3607 SDValue TPOffset;
3608 if (IsPCRel) {
3609 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3610 TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3612 } else {
3613 SDValue GOTPtr;
3614 if (is64bit) {
3615 setUsesTOCBasePtr(DAG);
3616 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3617 GOTPtr =
3618 DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3619 } else {
3620 if (!TM.isPositionIndependent())
3621 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3622 else if (picLevel == PICLevel::SmallPIC)
3623 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3624 else
3625 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3626 }
3627 TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3628 }
3629 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3630 }
3631
3632 if (Model == TLSModel::GeneralDynamic) {
3633 if (Subtarget.isUsingPCRelativeCalls()) {
3634 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3636 return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3637 }
3638
3639 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3640 SDValue GOTPtr;
3641 if (is64bit) {
3642 setUsesTOCBasePtr(DAG);
3643 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3644 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3645 GOTReg, TGA);
3646 } else {
3647 if (picLevel == PICLevel::SmallPIC)
3648 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3649 else
3650 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3651 }
3652 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3653 GOTPtr, TGA, TGA);
3654 }
3655
3656 if (Model == TLSModel::LocalDynamic) {
3657 if (Subtarget.isUsingPCRelativeCalls()) {
3658 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3660 SDValue MatPCRel =
3661 DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3662 return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3663 }
3664
3665 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3666 SDValue GOTPtr;
3667 if (is64bit) {
3668 setUsesTOCBasePtr(DAG);
3669 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3670 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3671 GOTReg, TGA);
3672 } else {
3673 if (picLevel == PICLevel::SmallPIC)
3674 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3675 else
3676 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3677 }
3678 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3679 PtrVT, GOTPtr, TGA, TGA);
3680 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3681 PtrVT, TLSAddr, TGA);
3682 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3683 }
3684
3685 llvm_unreachable("Unknown TLS model!");
3686}
3687
3688SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3689 SelectionDAG &DAG) const {
3690 EVT PtrVT = Op.getValueType();
3691 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);