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"
58#include "llvm/IR/CallingConv.h"
59#include "llvm/IR/Constant.h"
60#include "llvm/IR/Constants.h"
61#include "llvm/IR/DataLayout.h"
62#include "llvm/IR/DebugLoc.h"
64#include "llvm/IR/Function.h"
65#include "llvm/IR/GlobalValue.h"
66#include "llvm/IR/IRBuilder.h"
68#include "llvm/IR/Intrinsics.h"
69#include "llvm/IR/IntrinsicsPowerPC.h"
70#include "llvm/IR/Module.h"
71#include "llvm/IR/Type.h"
72#include "llvm/IR/Use.h"
73#include "llvm/IR/Value.h"
74#include "llvm/MC/MCContext.h"
75#include "llvm/MC/MCExpr.h"
84#include "llvm/Support/Debug.h"
86#include "llvm/Support/Format.h"
92#include <algorithm>
93#include <cassert>
94#include <cstdint>
95#include <iterator>
96#include <list>
97#include <optional>
98#include <utility>
99#include <vector>
100
101using namespace llvm;
102
103#define DEBUG_TYPE "ppc-lowering"
104
106 "disable-p10-store-forward",
107 cl::desc("disable P10 store forward-friendly conversion"), cl::Hidden,
108 cl::init(false));
109
110static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
111cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
112
113static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
114cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
115
116static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
117cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
118
119static cl::opt<bool> DisableSCO("disable-ppc-sco",
120cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
121
122static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
123cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
124
125static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
126cl::desc("use absolute jump tables on ppc"), cl::Hidden);
127
128static cl::opt<bool>
129 DisablePerfectShuffle("ppc-disable-perfect-shuffle",
130 cl::desc("disable vector permute decomposition"),
131 cl::init(true), cl::Hidden);
132
134 "disable-auto-paired-vec-st",
135 cl::desc("disable automatically generated 32byte paired vector stores"),
136 cl::init(true), cl::Hidden);
137
139 "ppc-min-jump-table-entries", cl::init(64), cl::Hidden,
140 cl::desc("Set minimum number of entries to use a jump table on PPC"));
141
143 "ppc-gather-alias-max-depth", cl::init(18), cl::Hidden,
144 cl::desc("max depth when checking alias info in GatherAllAliases()"));
145
147 "ppc-aix-shared-lib-tls-model-opt-limit", cl::init(1), cl::Hidden,
148 cl::desc("Set inclusive limit count of TLS local-dynamic access(es) in a "
149 "function to use initial-exec"));
150
151STATISTIC(NumTailCalls, "Number of tail calls");
152STATISTIC(NumSiblingCalls, "Number of sibling calls");
153STATISTIC(ShufflesHandledWithVPERM,
154 "Number of shuffles lowered to a VPERM or XXPERM");
155STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
156
157static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
158
159static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
160
161static const char AIXSSPCanaryWordName[] = "__ssp_canary_word";
162
163// A faster local-[exec|dynamic] TLS access sequence (enabled with the
164// -maix-small-local-[exec|dynamic]-tls option) can be produced for TLS
165// variables; consistent with the IBM XL compiler, we apply a max size of
166// slightly under 32KB.
168
169// FIXME: Remove this once the bug has been fixed!
171
173 const PPCSubtarget &STI)
174 : TargetLowering(TM), Subtarget(STI) {
175 // Initialize map that relates the PPC addressing modes to the computed flags
176 // of a load/store instruction. The map is used to determine the optimal
177 // addressing mode when selecting load and stores.
178 initializeAddrModeMap();
179 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
180 // arguments are at least 4/8 bytes aligned.
181 bool isPPC64 = Subtarget.isPPC64();
182 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
183 const MVT RegVT = Subtarget.getScalarIntVT();
184
185 // Set up the register classes.
186 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
187 if (!useSoftFloat()) {
188 if (hasSPE()) {
189 addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
190 // EFPU2 APU only supports f32
191 if (!Subtarget.hasEFPU2())
192 addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
193 } else {
194 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
195 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
196 }
197 }
198
200
201 // On P10, the default lowering generates better code using the
202 // setbc instruction.
203 if (!Subtarget.hasP10Vector()) {
205 if (isPPC64)
207 }
208
209 // Match BITREVERSE to customized fast code sequence in the td file.
212
213 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
215
216 // Custom lower inline assembly to check for special registers.
219
220 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
221 for (MVT VT : MVT::integer_valuetypes()) {
224 }
225
226 if (Subtarget.isISA3_0()) {
227 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
228 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
229 setTruncStoreAction(MVT::f64, MVT::f16, Legal);
230 setTruncStoreAction(MVT::f32, MVT::f16, Legal);
231 } else {
232 // No extending loads from f16 or HW conversions back and forth.
233 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
236 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
239 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
240 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
241 }
242
243 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
244
245 // PowerPC has pre-inc load and store's.
256 if (!Subtarget.hasSPE()) {
261 }
262
263 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
264 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
265 for (MVT VT : ScalarIntVTs) {
270 }
271
272 if (Subtarget.useCRBits()) {
274
275 if (isPPC64 || Subtarget.hasFPCVT()) {
280
282 AddPromotedToType(ISD::SINT_TO_FP, MVT::i1, RegVT);
284 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, RegVT);
285
290
292 AddPromotedToType(ISD::FP_TO_SINT, MVT::i1, RegVT);
294 AddPromotedToType(ISD::FP_TO_UINT, MVT::i1, RegVT);
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);
440 }
441
442 if (Subtarget.hasSPE())
443 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
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 (Subtarget.hasP9Vector() && isPPC64) ? Custom : Expand);
485 }
486
487 // CTPOP or CTTZ were introduced in P8/P9 respectively
488 if (Subtarget.isISA3_0()) {
489 setOperationAction(ISD::CTTZ , MVT::i32 , Legal);
490 setOperationAction(ISD::CTTZ , MVT::i64 , Legal);
491 } else {
492 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
493 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
494 }
495
496 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
499 } else {
502 }
503
504 // PowerPC does not have ROTR
507
508 if (!Subtarget.useCRBits()) {
509 // PowerPC does not have Select
514 }
515
516 // PowerPC wants to turn select_cc of FP into fsel when possible.
519
520 // PowerPC wants to optimize integer setcc a bit
521 if (!Subtarget.useCRBits())
523
524 if (Subtarget.hasFPU()) {
528
532 }
533
534 // PowerPC does not have BRCOND which requires SetCC
535 if (!Subtarget.useCRBits())
537
539
540 if (Subtarget.hasSPE()) {
541 // SPE has built-in conversions
548
549 // SPE supports signaling compare of f32/f64.
552 } else {
553 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
556
557 // PowerPC does not have [U|S]INT_TO_FP
562 }
563
564 if (Subtarget.hasDirectMove() && isPPC64) {
569 if (TM.Options.UnsafeFPMath) {
578 }
579 } else {
584 }
585
586 // We cannot sextinreg(i1). Expand to shifts.
588
589 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
590 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
591 // support continuation, user-level threading, and etc.. As a result, no
592 // other SjLj exception interfaces are implemented and please don't build
593 // your own exception handling based on them.
594 // LLVM/Clang supports zero-cost DWARF exception handling.
597
598 // We want to legalize GlobalAddress and ConstantPool nodes into the
599 // appropriate instructions to materialize the address.
610
611 // TRAP is legal.
612 setOperationAction(ISD::TRAP, MVT::Other, Legal);
613
614 // TRAMPOLINE is custom lowered.
617
618 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
620
621 if (Subtarget.is64BitELFABI()) {
622 // VAARG always uses double-word chunks, so promote anything smaller.
624 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
626 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
628 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
630 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
632 } else if (Subtarget.is32BitELFABI()) {
633 // VAARG is custom lowered with the 32-bit SVR4 ABI.
636 } else
638
639 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
640 if (Subtarget.is32BitELFABI())
642 else
644
645 // Use the default implementation.
646 setOperationAction(ISD::VAEND , MVT::Other, Expand);
655
656 // We want to custom lower some of our intrinsics.
662
663 // To handle counter-based loop conditions.
665
670
671 // Comparisons that require checking two conditions.
672 if (Subtarget.hasSPE()) {
677 }
690
693
694 if (Subtarget.has64BitSupport()) {
695 // They also have instructions for converting between i64 and fp.
704 // This is just the low 32 bits of a (signed) fp->i64 conversion.
705 // We cannot do this with Promote because i64 is not a legal type.
708
709 if (Subtarget.hasLFIWAX() || isPPC64) {
712 }
713 } else {
714 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
715 if (Subtarget.hasSPE()) {
718 } else {
721 }
722 }
723
724 // With the instructions enabled under FPCVT, we can do everything.
725 if (Subtarget.hasFPCVT()) {
726 if (Subtarget.has64BitSupport()) {
735 }
736
745 }
746
747 if (Subtarget.use64BitRegs()) {
748 // 64-bit PowerPC implementations can support i64 types directly
749 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
750 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
752 // 64-bit PowerPC wants to expand i128 shifts itself.
756 } else {
757 // 32-bit PowerPC wants to expand i64 shifts itself.
761 }
762
763 // PowerPC has better expansions for funnel shifts than the generic
764 // TargetLowering::expandFunnelShift.
765 if (Subtarget.has64BitSupport()) {
768 }
771
772 if (Subtarget.hasVSX()) {
777 }
778
779 if (Subtarget.hasAltivec()) {
780 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
785 }
786 // First set operation action for all vector types to expand. Then we
787 // will selectively turn on ones that can be effectively codegen'd.
789 // add/sub are legal for all supported vector VT's.
792
793 // For v2i64, these are only valid with P8Vector. This is corrected after
794 // the loop.
795 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
800 }
801 else {
806 }
807
808 if (Subtarget.hasVSX()) {
811 }
812
813 // Vector instructions introduced in P8
814 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
817 }
818 else {
821 }
822
823 // Vector instructions introduced in P9
824 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
826 else
828
829 // We promote all shuffles to v16i8.
831 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
832
833 // We promote all non-typed operations to v4i32.
835 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
837 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
839 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
841 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
843 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
846 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
848 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
849
850 // No other operations are legal.
889
890 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
891 setTruncStoreAction(VT, InnerVT, Expand);
894 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
895 }
896 }
898 if (!Subtarget.hasP8Vector()) {
899 setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
900 setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
901 setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
902 setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
903 }
904
905 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
906 // with merges, splats, etc.
908
909 // Vector truncates to sub-word integer that fit in an Altivec/VSX register
910 // are cheap, so handle them before they get expanded to scalar.
916
917 setOperationAction(ISD::AND , MVT::v4i32, Legal);
918 setOperationAction(ISD::OR , MVT::v4i32, Legal);
919 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
920 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
922 Subtarget.useCRBits() ? Legal : Expand);
923 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
933 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
936
937 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
938 setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
939 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
940 if (Subtarget.hasAltivec())
941 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
943 // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
944 if (Subtarget.hasP8Altivec())
945 setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
946
947 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
948 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
949 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
950 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
951
952 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
953 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
954
955 if (Subtarget.hasVSX()) {
956 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
957 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
959 }
960
961 if (Subtarget.hasP8Altivec())
962 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
963 else
964 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
965
966 if (Subtarget.isISA3_1()) {
967 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
968 setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
969 setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
970 setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
971 setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
972 setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
973 setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
974 setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
975 setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
976 setOperationAction(ISD::UREM, MVT::v2i64, Legal);
977 setOperationAction(ISD::SREM, MVT::v2i64, Legal);
978 setOperationAction(ISD::UREM, MVT::v4i32, Legal);
979 setOperationAction(ISD::SREM, MVT::v4i32, Legal);
980 setOperationAction(ISD::UREM, MVT::v1i128, Legal);
981 setOperationAction(ISD::SREM, MVT::v1i128, Legal);
982 setOperationAction(ISD::UDIV, MVT::v1i128, Legal);
983 setOperationAction(ISD::SDIV, MVT::v1i128, Legal);
984 setOperationAction(ISD::ROTL, MVT::v1i128, Legal);
985 }
986
987 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
988 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
989
992 // LE is P8+/64-bit so direct moves are supported and these operations
993 // are legal. The custom transformation requires 64-bit since we need a
994 // pair of stores that will cover a 128-bit load for P10.
995 if (!DisableP10StoreForward && isPPC64 && !Subtarget.isLittleEndian()) {
999 }
1000
1005
1006 // Altivec does not contain unordered floating-point compare instructions
1007 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
1008 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
1009 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
1010 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
1011
1012 if (Subtarget.hasVSX()) {
1015 if (Subtarget.hasP8Vector()) {
1018 }
1019 if (Subtarget.hasDirectMove() && isPPC64) {
1028 }
1030
1031 // The nearbyint variants are not allowed to raise the inexact exception
1032 // so we can only code-gen them with unsafe math.
1033 if (TM.Options.UnsafeFPMath) {
1036 }
1037
1038 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1039 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1040 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1042 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1043 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
1046
1048 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1049 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1052
1053 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
1054 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1055
1056 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
1057 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
1058
1059 // Share the Altivec comparison restrictions.
1060 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
1061 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
1062 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
1063 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
1064
1065 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1066 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
1067
1069
1070 if (Subtarget.hasP8Vector())
1071 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
1072
1073 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
1074
1075 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
1076 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
1077 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
1078
1079 if (Subtarget.hasP8Altivec()) {
1080 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1081 setOperationAction(ISD::SRA, MVT::v2i64, Legal);
1082 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1083
1084 // 128 bit shifts can be accomplished via 3 instructions for SHL and
1085 // SRL, but not for SRA because of the instructions available:
1086 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
1087 // doing
1088 setOperationAction(ISD::SHL, MVT::v1i128, Expand);
1089 setOperationAction(ISD::SRL, MVT::v1i128, Expand);
1090 setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1091
1092 setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
1093 }
1094 else {
1095 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
1096 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
1097 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
1098
1099 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1100
1101 // VSX v2i64 only supports non-arithmetic operations.
1102 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
1103 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
1104 }
1105
1106 if (Subtarget.isISA3_1())
1107 setOperationAction(ISD::SETCC, MVT::v1i128, Legal);
1108 else
1109 setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1110
1111 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1112 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1114 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1115
1117
1126
1127 // Custom handling for partial vectors of integers converted to
1128 // floating point. We already have optimal handling for v2i32 through
1129 // the DAG combine, so those aren't necessary.
1146
1147 setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1148 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1149 setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1150 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1153
1156
1157 // Handle constrained floating-point operations of vector.
1158 // The predictor is `hasVSX` because altivec instruction has
1159 // no exception but VSX vector instruction has.
1173
1187
1188 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1189 addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1190
1191 for (MVT FPT : MVT::fp_valuetypes())
1192 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1193
1194 // Expand the SELECT to SELECT_CC
1196
1197 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1198 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1199
1200 // No implementation for these ops for PowerPC.
1202 setOperationAction(ISD::FSIN, MVT::f128, Expand);
1203 setOperationAction(ISD::FCOS, MVT::f128, Expand);
1204 setOperationAction(ISD::FPOW, MVT::f128, Expand);
1206 setOperationAction(ISD::FREM, MVT::f128, Expand);
1207 }
1208
1209 if (Subtarget.hasP8Altivec()) {
1210 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1211 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1212 }
1213
1214 if (Subtarget.hasP9Vector()) {
1217
1218 // Test data class instructions store results in CR bits.
1219 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;
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 case PPCISD::SETBC:
1854 return "PPCISD::SETBC";
1855 case PPCISD::SETBCR:
1856 return "PPCISD::SETBCR";
1857 }
1858 return nullptr;
1859}
1860
1862 EVT VT) const {
1863 if (!VT.isVector())
1864 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1865
1867}
1868
1870 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1871 return true;
1872}
1873
1874//===----------------------------------------------------------------------===//
1875// Node matching predicates, for use by the tblgen matching code.
1876//===----------------------------------------------------------------------===//
1877
1878/// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1880 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1881 return CFP->getValueAPF().isZero();
1882 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1883 // Maybe this has already been legalized into the constant pool?
1884 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1885 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1886 return CFP->getValueAPF().isZero();
1887 }
1888 return false;
1889}
1890
1891/// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1892/// true if Op is undef or if it matches the specified value.
1893static bool isConstantOrUndef(int Op, int Val) {
1894 return Op < 0 || Op == Val;
1895}
1896
1897/// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1898/// VPKUHUM instruction.
1899/// The ShuffleKind distinguishes between big-endian operations with
1900/// two different inputs (0), either-endian operations with two identical
1901/// inputs (1), and little-endian operations with two different inputs (2).
1902/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1904 SelectionDAG &DAG) {
1905 bool IsLE = DAG.getDataLayout().isLittleEndian();
1906 if (ShuffleKind == 0) {
1907 if (IsLE)
1908 return false;
1909 for (unsigned i = 0; i != 16; ++i)
1910 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1911 return false;
1912 } else if (ShuffleKind == 2) {
1913 if (!IsLE)
1914 return false;
1915 for (unsigned i = 0; i != 16; ++i)
1916 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1917 return false;
1918 } else if (ShuffleKind == 1) {
1919 unsigned j = IsLE ? 0 : 1;
1920 for (unsigned i = 0; i != 8; ++i)
1921 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1922 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1923 return false;
1924 }
1925 return true;
1926}
1927
1928/// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1929/// VPKUWUM instruction.
1930/// The ShuffleKind distinguishes between big-endian operations with
1931/// two different inputs (0), either-endian operations with two identical
1932/// inputs (1), and little-endian operations with two different inputs (2).
1933/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1935 SelectionDAG &DAG) {
1936 bool IsLE = DAG.getDataLayout().isLittleEndian();
1937 if (ShuffleKind == 0) {
1938 if (IsLE)
1939 return false;
1940 for (unsigned i = 0; i != 16; i += 2)
1941 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1942 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1943 return false;
1944 } else if (ShuffleKind == 2) {
1945 if (!IsLE)
1946 return false;
1947 for (unsigned i = 0; i != 16; i += 2)
1948 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1949 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1950 return false;
1951 } else if (ShuffleKind == 1) {
1952 unsigned j = IsLE ? 0 : 2;
1953 for (unsigned i = 0; i != 8; i += 2)
1954 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1955 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1956 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1957 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1958 return false;
1959 }
1960 return true;
1961}
1962
1963/// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1964/// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1965/// current subtarget.
1966///
1967/// The ShuffleKind distinguishes between big-endian operations with
1968/// two different inputs (0), either-endian operations with two identical
1969/// inputs (1), and little-endian operations with two different inputs (2).
1970/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1972 SelectionDAG &DAG) {
1973 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>();
1974 if (!Subtarget.hasP8Vector())
1975 return false;
1976
1977 bool IsLE = DAG.getDataLayout().isLittleEndian();
1978 if (ShuffleKind == 0) {
1979 if (IsLE)
1980 return false;
1981 for (unsigned i = 0; i != 16; i += 4)
1982 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) ||
1983 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) ||
1984 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) ||
1985 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7))
1986 return false;
1987 } else if (ShuffleKind == 2) {
1988 if (!IsLE)
1989 return false;
1990 for (unsigned i = 0; i != 16; i += 4)
1991 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1992 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) ||
1993 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) ||
1994 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3))
1995 return false;
1996 } else if (ShuffleKind == 1) {
1997 unsigned j = IsLE ? 0 : 4;
1998 for (unsigned i = 0; i != 8; i += 4)
1999 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
2000 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
2001 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) ||
2002 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) ||
2003 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
2004 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) ||
2005 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
2006 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
2007 return false;
2008 }
2009 return true;
2010}
2011
2012/// isVMerge - Common function, used to match vmrg* shuffles.
2013///
2014static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
2015 unsigned LHSStart, unsigned RHSStart) {
2016 if (N->getValueType(0) != MVT::v16i8)
2017 return false;
2018 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
2019 "Unsupported merge size!");
2020
2021 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
2022 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
2023 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
2024 LHSStart+j+i*UnitSize) ||
2025 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
2026 RHSStart+j+i*UnitSize))
2027 return false;
2028 }
2029 return true;
2030}
2031
2032/// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
2033/// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
2034/// The ShuffleKind distinguishes between big-endian merges with two
2035/// different inputs (0), either-endian merges with two identical inputs (1),
2036/// and little-endian merges with two different inputs (2). For the latter,
2037/// the input operands are swapped (see PPCInstrAltivec.td).
2039 unsigned ShuffleKind, SelectionDAG &DAG) {
2040 if (DAG.getDataLayout().isLittleEndian()) {
2041 if (ShuffleKind == 1) // unary
2042 return isVMerge(N, UnitSize, 0, 0);
2043 else if (ShuffleKind == 2) // swapped
2044 return isVMerge(N, UnitSize, 0, 16);
2045 else
2046 return false;
2047 } else {
2048 if (ShuffleKind == 1) // unary
2049 return isVMerge(N, UnitSize, 8, 8);
2050 else if (ShuffleKind == 0) // normal
2051 return isVMerge(N, UnitSize, 8, 24);
2052 else
2053 return false;
2054 }
2055}
2056
2057/// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
2058/// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
2059/// The ShuffleKind distinguishes between big-endian merges with two
2060/// different inputs (0), either-endian merges with two identical inputs (1),
2061/// and little-endian merges with two different inputs (2). For the latter,
2062/// the input operands are swapped (see PPCInstrAltivec.td).
2064 unsigned ShuffleKind, SelectionDAG &DAG) {
2065 if (DAG.getDataLayout().isLittleEndian()) {
2066 if (ShuffleKind == 1) // unary
2067 return isVMerge(N, UnitSize, 8, 8);
2068 else if (ShuffleKind == 2) // swapped
2069 return isVMerge(N, UnitSize, 8, 24);
2070 else
2071 return false;
2072 } else {
2073 if (ShuffleKind == 1) // unary
2074 return isVMerge(N, UnitSize, 0, 0);
2075 else if (ShuffleKind == 0) // normal
2076 return isVMerge(N, UnitSize, 0, 16);
2077 else
2078 return false;
2079 }
2080}
2081
2082/**
2083 * Common function used to match vmrgew and vmrgow shuffles
2084 *
2085 * The indexOffset determines whether to look for even or odd words in
2086 * the shuffle mask. This is based on the of the endianness of the target
2087 * machine.
2088 * - Little Endian:
2089 * - Use offset of 0 to check for odd elements
2090 * - Use offset of 4 to check for even elements
2091 * - Big Endian:
2092 * - Use offset of 0 to check for even elements
2093 * - Use offset of 4 to check for odd elements
2094 * A detailed description of the vector element ordering for little endian and
2095 * big endian can be found at
2096 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
2097 * Targeting your applications - what little endian and big endian IBM XL C/C++
2098 * compiler differences mean to you
2099 *
2100 * The mask to the shuffle vector instruction specifies the indices of the
2101 * elements from the two input vectors to place in the result. The elements are
2102 * numbered in array-access order, starting with the first vector. These vectors
2103 * are always of type v16i8, thus each vector will contain 16 elements of size
2104 * 8. More info on the shuffle vector can be found in the
2105 * http://llvm.org/docs/LangRef.html#shufflevector-instruction
2106 * Language Reference.
2107 *
2108 * The RHSStartValue indicates whether the same input vectors are used (unary)
2109 * or two different input vectors are used, based on the following:
2110 * - If the instruction uses the same vector for both inputs, the range of the
2111 * indices will be 0 to 15. In this case, the RHSStart value passed should
2112 * be 0.
2113 * - If the instruction has two different vectors then the range of the
2114 * indices will be 0 to 31. In this case, the RHSStart value passed should
2115 * be 16 (indices 0-15 specify elements in the first vector while indices 16
2116 * to 31 specify elements in the second vector).
2117 *
2118 * \param[in] N The shuffle vector SD Node to analyze
2119 * \param[in] IndexOffset Specifies whether to look for even or odd elements
2120 * \param[in] RHSStartValue Specifies the starting index for the righthand input
2121 * vector to the shuffle_vector instruction
2122 * \return true iff this shuffle vector represents an even or odd word merge
2123 */
2124static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
2125 unsigned RHSStartValue) {
2126 if (N->getValueType(0) != MVT::v16i8)
2127 return false;
2128
2129 for (unsigned i = 0; i < 2; ++i)
2130 for (unsigned j = 0; j < 4; ++j)
2131 if (!isConstantOrUndef(N->getMaskElt(i*4+j),
2132 i*RHSStartValue+j+IndexOffset) ||
2133 !isConstantOrUndef(N->getMaskElt(i*4+j+8),
2134 i*RHSStartValue+j+IndexOffset+8))
2135 return false;
2136 return true;
2137}
2138
2139/**
2140 * Determine if the specified shuffle mask is suitable for the vmrgew or
2141 * vmrgow instructions.
2142 *
2143 * \param[in] N The shuffle vector SD Node to analyze
2144 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
2145 * \param[in] ShuffleKind Identify the type of merge:
2146 * - 0 = big-endian merge with two different inputs;
2147 * - 1 = either-endian merge with two identical inputs;
2148 * - 2 = little-endian merge with two different inputs (inputs are swapped for
2149 * little-endian merges).
2150 * \param[in] DAG The current SelectionDAG
2151 * \return true iff this shuffle mask
2152 */
2154 unsigned ShuffleKind, SelectionDAG &DAG) {
2155 if (DAG.getDataLayout().isLittleEndian()) {
2156 unsigned indexOffset = CheckEven ? 4 : 0;
2157 if (ShuffleKind == 1) // Unary
2158 return isVMerge(N, indexOffset, 0);
2159 else if (ShuffleKind == 2) // swapped
2160 return isVMerge(N, indexOffset, 16);
2161 else
2162 return false;
2163 }
2164 else {
2165 unsigned indexOffset = CheckEven ? 0 : 4;
2166 if (ShuffleKind == 1) // Unary
2167 return isVMerge(N, indexOffset, 0);
2168 else if (ShuffleKind == 0) // Normal
2169 return isVMerge(N, indexOffset, 16);
2170 else
2171 return false;
2172 }
2173 return false;
2174}
2175
2176/// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
2177/// amount, otherwise return -1.
2178/// The ShuffleKind distinguishes between big-endian operations with two
2179/// different inputs (0), either-endian operations with two identical inputs
2180/// (1), and little-endian operations with two different inputs (2). For the
2181/// latter, the input operands are swapped (see PPCInstrAltivec.td).
2182int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
2183 SelectionDAG &DAG) {
2184 if (N->getValueType(0) != MVT::v16i8)
2185 return -1;
2186
2187 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2188
2189 // Find the first non-undef value in the shuffle mask.
2190 unsigned i;
2191 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
2192 /*search*/;
2193
2194 if (i == 16) return -1; // all undef.
2195
2196 // Otherwise, check to see if the rest of the elements are consecutively
2197 // numbered from this value.
2198 unsigned ShiftAmt = SVOp->getMaskElt(i);
2199 if (ShiftAmt < i) return -1;
2200
2201 ShiftAmt -= i;
2202 bool isLE = DAG.getDataLayout().isLittleEndian();
2203
2204 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
2205 // Check the rest of the elements to see if they are consecutive.
2206 for (++i; i != 16; ++i)
2207 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2208 return -1;
2209 } else if (ShuffleKind == 1) {
2210 // Check the rest of the elements to see if they are consecutive.
2211 for (++i; i != 16; ++i)
2212 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
2213 return -1;
2214 } else
2215 return -1;
2216
2217 if (isLE)
2218 ShiftAmt = 16 - ShiftAmt;
2219
2220 return ShiftAmt;
2221}
2222
2223/// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
2224/// specifies a splat of a single element that is suitable for input to
2225/// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
2227 EVT VT = N->getValueType(0);
2228 if (VT == MVT::v2i64 || VT == MVT::v2f64)
2229 return EltSize == 8 && N->getMaskElt(0) == N->getMaskElt(1);
2230
2231 assert(VT == MVT::v16i8 && isPowerOf2_32(EltSize) &&
2232 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
2233
2234 // The consecutive indices need to specify an element, not part of two
2235 // different elements. So abandon ship early if this isn't the case.
2236 if (N->getMaskElt(0) % EltSize != 0)
2237 return false;
2238
2239 // This is a splat operation if each element of the permute is the same, and
2240 // if the value doesn't reference the second vector.
2241 unsigned ElementBase = N->getMaskElt(0);
2242
2243 // FIXME: Handle UNDEF elements too!
2244 if (ElementBase >= 16)
2245 return false;
2246
2247 // Check that the indices are consecutive, in the case of a multi-byte element
2248 // splatted with a v16i8 mask.
2249 for (unsigned i = 1; i != EltSize; ++i)
2250 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2251 return false;
2252
2253 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2254 if (N->getMaskElt(i) < 0) continue;
2255 for (unsigned j = 0; j != EltSize; ++j)
2256 if (N->getMaskElt(i+j) != N->getMaskElt(j))
2257 return false;
2258 }
2259 return true;
2260}
2261
2262/// Check that the mask is shuffling N byte elements. Within each N byte
2263/// element of the mask, the indices could be either in increasing or
2264/// decreasing order as long as they are consecutive.
2265/// \param[in] N the shuffle vector SD Node to analyze
2266/// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2267/// Word/DoubleWord/QuadWord).
2268/// \param[in] StepLen the delta indices number among the N byte element, if
2269/// the mask is in increasing/decreasing order then it is 1/-1.
2270/// \return true iff the mask is shuffling N byte elements.
2271static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
2272 int StepLen) {
2273 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
2274 "Unexpected element width.");
2275 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2276
2277 unsigned NumOfElem = 16 / Width;
2278 unsigned MaskVal[16]; // Width is never greater than 16
2279 for (unsigned i = 0; i < NumOfElem; ++i) {
2280 MaskVal[0] = N->getMaskElt(i * Width);
2281 if ((StepLen == 1) && (MaskVal[0] % Width)) {
2282 return false;
2283 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2284 return false;
2285 }
2286
2287 for (unsigned int j = 1; j < Width; ++j) {
2288 MaskVal[j] = N->getMaskElt(i * Width + j);
2289 if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2290 return false;
2291 }
2292 }
2293 }
2294
2295 return true;
2296}
2297
2298bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2299 unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2300 if (!isNByteElemShuffleMask(N, 4, 1))
2301 return false;
2302
2303 // Now we look at mask elements 0,4,8,12
2304 unsigned M0 = N->getMaskElt(0) / 4;
2305 unsigned M1 = N->getMaskElt(4) / 4;
2306 unsigned M2 = N->getMaskElt(8) / 4;
2307 unsigned M3 = N->getMaskElt(12) / 4;
2308 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2309 unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2310
2311 // Below, let H and L be arbitrary elements of the shuffle mask
2312 // where H is in the range [4,7] and L is in the range [0,3].
2313 // H, 1, 2, 3 or L, 5, 6, 7
2314 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2315 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2316 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2317 InsertAtByte = IsLE ? 12 : 0;
2318 Swap = M0 < 4;
2319 return true;
2320 }
2321 // 0, H, 2, 3 or 4, L, 6, 7
2322 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2323 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2324 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2325 InsertAtByte = IsLE ? 8 : 4;
2326 Swap = M1 < 4;
2327 return true;
2328 }
2329 // 0, 1, H, 3 or 4, 5, L, 7
2330 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2331 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2332 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2333 InsertAtByte = IsLE ? 4 : 8;
2334 Swap = M2 < 4;
2335 return true;
2336 }
2337 // 0, 1, 2, H or 4, 5, 6, L
2338 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2339 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2340 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2341 InsertAtByte = IsLE ? 0 : 12;
2342 Swap = M3 < 4;
2343 return true;
2344 }
2345
2346 // If both vector operands for the shuffle are the same vector, the mask will
2347 // contain only elements from the first one and the second one will be undef.
2348 if (N->getOperand(1).isUndef()) {
2349 ShiftElts = 0;
2350 Swap = true;
2351 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2352 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2353 InsertAtByte = IsLE ? 12 : 0;
2354 return true;
2355 }
2356 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2357 InsertAtByte = IsLE ? 8 : 4;
2358 return true;
2359 }
2360 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2361 InsertAtByte = IsLE ? 4 : 8;
2362 return true;
2363 }
2364 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2365 InsertAtByte = IsLE ? 0 : 12;
2366 return true;
2367 }
2368 }
2369
2370 return false;
2371}
2372
2374 bool &Swap, bool IsLE) {
2375 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2376 // Ensure each byte index of the word is consecutive.
2377 if (!isNByteElemShuffleMask(N, 4, 1))
2378 return false;
2379
2380 // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2381 unsigned M0 = N->getMaskElt(0) / 4;
2382 unsigned M1 = N->getMaskElt(4) / 4;
2383 unsigned M2 = N->getMaskElt(8) / 4;
2384 unsigned M3 = N->getMaskElt(12) / 4;
2385
2386 // If both vector operands for the shuffle are the same vector, the mask will
2387 // contain only elements from the first one and the second one will be undef.
2388 if (N->getOperand(1).isUndef()) {
2389 assert(M0 < 4 && "Indexing into an undef vector?");
2390 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2391 return false;
2392
2393 ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2394 Swap = false;
2395 return true;
2396 }
2397
2398 // Ensure each word index of the ShuffleVector Mask is consecutive.
2399 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2400 return false;
2401
2402 if (IsLE) {
2403 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2404 // Input vectors don't need to be swapped if the leading element
2405 // of the result is one of the 3 left elements of the second vector
2406 // (or if there is no shift to be done at all).
2407 Swap = false;
2408 ShiftElts = (8 - M0) % 8;
2409 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2410 // Input vectors need to be swapped if the leading element
2411 // of the result is one of the 3 left elements of the first vector
2412 // (or if we're shifting by 4 - thereby simply swapping the vectors).
2413 Swap = true;
2414 ShiftElts = (4 - M0) % 4;
2415 }
2416
2417 return true;
2418 } else { // BE
2419 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2420 // Input vectors don't need to be swapped if the leading element
2421 // of the result is one of the 4 elements of the first vector.
2422 Swap = false;
2423 ShiftElts = M0;
2424 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2425 // Input vectors need to be swapped if the leading element
2426 // of the result is one of the 4 elements of the right vector.
2427 Swap = true;
2428 ShiftElts = M0 - 4;
2429 }
2430
2431 return true;
2432 }
2433}
2434
2436 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2437
2438 if (!isNByteElemShuffleMask(N, Width, -1))
2439 return false;
2440
2441 for (int i = 0; i < 16; i += Width)
2442 if (N->getMaskElt(i) != i + Width - 1)
2443 return false;
2444
2445 return true;
2446}
2447
2449 return isXXBRShuffleMaskHelper(N, 2);
2450}
2451
2453 return isXXBRShuffleMaskHelper(N, 4);
2454}
2455
2457 return isXXBRShuffleMaskHelper(N, 8);
2458}
2459
2461 return isXXBRShuffleMaskHelper(N, 16);
2462}
2463
2464/// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2465/// if the inputs to the instruction should be swapped and set \p DM to the
2466/// value for the immediate.
2467/// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2468/// AND element 0 of the result comes from the first input (LE) or second input
2469/// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2470/// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2471/// mask.
2473 bool &Swap, bool IsLE) {
2474 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2475
2476 // Ensure each byte index of the double word is consecutive.
2477 if (!isNByteElemShuffleMask(N, 8, 1))
2478 return false;
2479
2480 unsigned M0 = N->getMaskElt(0) / 8;
2481 unsigned M1 = N->getMaskElt(8) / 8;
2482 assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2483
2484 // If both vector operands for the shuffle are the same vector, the mask will
2485 // contain only elements from the first one and the second one will be undef.
2486 if (N->getOperand(1).isUndef()) {
2487 if ((M0 | M1) < 2) {
2488 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2489 Swap = false;
2490 return true;
2491 } else
2492 return false;
2493 }
2494
2495 if (IsLE) {
2496 if (M0 > 1 && M1 < 2) {
2497 Swap = false;
2498 } else if (M0 < 2 && M1 > 1) {
2499 M0 = (M0 + 2) % 4;
2500 M1 = (M1 + 2) % 4;
2501 Swap = true;
2502 } else
2503 return false;
2504
2505 // Note: if control flow comes here that means Swap is already set above
2506 DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2507 return true;
2508 } else { // BE
2509 if (M0 < 2 && M1 > 1) {
2510 Swap = false;
2511 } else if (M0 > 1 && M1 < 2) {
2512 M0 = (M0 + 2) % 4;
2513 M1 = (M1 + 2) % 4;
2514 Swap = true;
2515 } else
2516 return false;
2517
2518 // Note: if control flow comes here that means Swap is already set above
2519 DM = (M0 << 1) + (M1 & 1);
2520 return true;
2521 }
2522}
2523
2524
2525/// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2526/// appropriate for PPC mnemonics (which have a big endian bias - namely
2527/// elements are counted from the left of the vector register).
2528unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2529 SelectionDAG &DAG) {
2530 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2531 assert(isSplatShuffleMask(SVOp, EltSize));
2532 EVT VT = SVOp->getValueType(0);
2533
2534 if (VT == MVT::v2i64 || VT == MVT::v2f64)
2535 return DAG.getDataLayout().isLittleEndian() ? 1 - SVOp->getMaskElt(0)
2536 : SVOp->getMaskElt(0);
2537
2538 if (DAG.getDataLayout().isLittleEndian())
2539 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2540 else
2541 return SVOp->getMaskElt(0) / EltSize;
2542}
2543
2544/// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2545/// by using a vspltis[bhw] instruction of the specified element size, return
2546/// the constant being splatted. The ByteSize field indicates the number of
2547/// bytes of each element [124] -> [bhw].
2549 SDValue OpVal;
2550
2551 // If ByteSize of the splat is bigger than the element size of the
2552 // build_vector, then we have a case where we are checking for a splat where
2553 // multiple elements of the buildvector are folded together into a single
2554 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2555 unsigned EltSize = 16/N->getNumOperands();
2556 if (EltSize < ByteSize) {
2557 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
2558 SDValue UniquedVals[4];
2559 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2560
2561 // See if all of the elements in the buildvector agree across.
2562 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2563 if (N->getOperand(i).isUndef()) continue;
2564 // If the element isn't a constant, bail fully out.
2565 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2566
2567 if (!UniquedVals[i&(Multiple-1)].getNode())
2568 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2569 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2570 return SDValue(); // no match.
2571 }
2572
2573 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2574 // either constant or undef values that are identical for each chunk. See
2575 // if these chunks can form into a larger vspltis*.
2576
2577 // Check to see if all of the leading entries are either 0 or -1. If
2578 // neither, then this won't fit into the immediate field.
2579 bool LeadingZero = true;
2580 bool LeadingOnes = true;
2581 for (unsigned i = 0; i != Multiple-1; ++i) {
2582 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
2583
2584 LeadingZero &= isNullConstant(UniquedVals[i]);
2585 LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2586 }
2587 // Finally, check the least significant entry.
2588 if (LeadingZero) {
2589 if (!UniquedVals[Multiple-1].getNode())
2590 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
2591 int Val = UniquedVals[Multiple - 1]->getAsZExtVal();
2592 if (Val < 16) // 0,0,0,4 -> vspltisw(4)
2593 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2594 }
2595 if (LeadingOnes) {
2596 if (!UniquedVals[Multiple-1].getNode())
2597 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2598 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2599 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
2600 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2601 }
2602
2603 return SDValue();
2604 }
2605
2606 // Check to see if this buildvec has a single non-undef value in its elements.
2607 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2608 if (N->getOperand(i).isUndef()) continue;
2609 if (!OpVal.getNode())
2610 OpVal = N->getOperand(i);
2611 else if (OpVal != N->getOperand(i))
2612 return SDValue();
2613 }
2614
2615 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
2616
2617 unsigned ValSizeInBytes = EltSize;
2618 uint64_t Value = 0;
2619 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2620 Value = CN->getZExtValue();
2621 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2622 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2623 Value = llvm::bit_cast<uint32_t>(CN->getValueAPF().convertToFloat());
2624 }
2625
2626 // If the splat value is larger than the element value, then we can never do
2627 // this splat. The only case that we could fit the replicated bits into our
2628 // immediate field for would be zero, and we prefer to use vxor for it.
2629 if (ValSizeInBytes < ByteSize) return SDValue();
2630
2631 // If the element value is larger than the splat value, check if it consists
2632 // of a repeated bit pattern of size ByteSize.
2633 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2634 return SDValue();
2635
2636 // Properly sign extend the value.
2637 int MaskVal = SignExtend32(Value, ByteSize * 8);
2638
2639 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2640 if (MaskVal == 0) return SDValue();
2641
2642 // Finally, if this value fits in a 5 bit sext field, return it
2643 if (SignExtend32<5>(MaskVal) == MaskVal)
2644 return DAG.getSignedTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2645 return SDValue();
2646}
2647
2648//===----------------------------------------------------------------------===//
2649// Addressing Mode Selection
2650//===----------------------------------------------------------------------===//
2651
2652/// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2653/// or 64-bit immediate, and if the value can be accurately represented as a
2654/// sign extension from a 16-bit value. If so, this returns true and the
2655/// immediate.
2656bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2657 if (!isa<ConstantSDNode>(N))
2658 return false;
2659
2660 Imm = (int16_t)N->getAsZExtVal();
2661 if (N->getValueType(0) == MVT::i32)
2662 return Imm == (int32_t)N->getAsZExtVal();
2663 else
2664 return Imm == (int64_t)N->getAsZExtVal();
2665}
2667 return isIntS16Immediate(Op.getNode(), Imm);
2668}
2669
2670/// Used when computing address flags for selecting loads and stores.
2671/// If we have an OR, check if the LHS and RHS are provably disjoint.
2672/// An OR of two provably disjoint values is equivalent to an ADD.
2673/// Most PPC load/store instructions compute the effective address as a sum,
2674/// so doing this conversion is useful.
2675static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) {
2676 if (N.getOpcode() != ISD::OR)
2677 return false;
2678 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2679 if (!LHSKnown.Zero.getBoolValue())
2680 return false;
2681 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2682 return (~(LHSKnown.Zero | RHSKnown.Zero) == 0);
2683}
2684
2685/// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2686/// be represented as an indexed [r+r] operation.
2688 SDValue &Index,
2689 SelectionDAG &DAG) const {
2690 for (SDNode *U : N->users()) {
2691 if (MemSDNode *Memop = dyn_cast<MemSDNode>(U)) {
2692 if (Memop->getMemoryVT() == MVT::f64) {
2693 Base = N.getOperand(0);
2694 Index = N.getOperand(1);
2695 return true;
2696 }
2697 }
2698 }
2699 return false;
2700}
2701
2702/// isIntS34Immediate - This method tests if value of node given can be
2703/// accurately represented as a sign extension from a 34-bit value. If so,
2704/// this returns true and the immediate.
2705bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2706 if (!isa<ConstantSDNode>(N))
2707 return false;
2708
2709 Imm = (int64_t)cast<ConstantSDNode>(N)->getSExtValue();
2710 return isInt<34>(Imm);
2711}
2713 return isIntS34Immediate(Op.getNode(), Imm);
2714}
2715
2716/// SelectAddressRegReg - Given the specified addressed, check to see if it
2717/// can be represented as an indexed [r+r] operation. Returns false if it
2718/// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2719/// non-zero and N can be represented by a base register plus a signed 16-bit
2720/// displacement, make a more precise judgement by checking (displacement % \p
2721/// EncodingAlignment).
2723 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2724 MaybeAlign EncodingAlignment) const {
2725 // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2726 // a [pc+imm].
2728 return false;
2729
2730 int16_t Imm = 0;
2731 if (N.getOpcode() == ISD::ADD) {
2732 // Is there any SPE load/store (f64), which can't handle 16bit offset?
2733 // SPE load/store can only handle 8-bit offsets.
2734 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2735 return true;
2736 if (isIntS16Immediate(N.getOperand(1), Imm) &&
2737 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2738 return false; // r+i
2739 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2740 return false; // r+i
2741
2742 Base = N.getOperand(0);
2743 Index = N.getOperand(1);
2744 return true;
2745 } else if (N.getOpcode() == ISD::OR) {
2746 if (isIntS16Immediate(N.getOperand(1), Imm) &&
2747 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2748 return false; // r+i can fold it if we can.
2749
2750 // If this is an or of disjoint bitfields, we can codegen this as an add
2751 // (for better address arithmetic) if the LHS and RHS of the OR are provably
2752 // disjoint.
2753 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2754
2755 if (LHSKnown.Zero.getBoolValue()) {
2756 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2757 // If all of the bits are known zero on the LHS or RHS, the add won't
2758 // carry.
2759 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2760 Base = N.getOperand(0);
2761 Index = N.getOperand(1);
2762 return true;
2763 }
2764 }
2765 }
2766
2767 return false;
2768}
2769
2770// If we happen to be doing an i64 load or store into a stack slot that has
2771// less than a 4-byte alignment, then the frame-index elimination may need to
2772// use an indexed load or store instruction (because the offset may not be a
2773// multiple of 4). The extra register needed to hold the offset comes from the
2774// register scavenger, and it is possible that the scavenger will need to use
2775// an emergency spill slot. As a result, we need to make sure that a spill slot
2776// is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2777// stack slot.
2778static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2779 // FIXME: This does not handle the LWA case.
2780 if (VT != MVT::i64)
2781 return;
2782
2783 // NOTE: We'll exclude negative FIs here, which come from argument
2784 // lowering, because there are no known test cases triggering this problem
2785 // using packed structures (or similar). We can remove this exclusion if
2786 // we find such a test case. The reason why this is so test-case driven is
2787 // because this entire 'fixup' is only to prevent crashes (from the
2788 // register scavenger) on not-really-valid inputs. For example, if we have:
2789 // %a = alloca i1
2790 // %b = bitcast i1* %a to i64*
2791 // store i64* a, i64 b
2792 // then the store should really be marked as 'align 1', but is not. If it
2793 // were marked as 'align 1' then the indexed form would have been
2794 // instruction-selected initially, and the problem this 'fixup' is preventing
2795 // won't happen regardless.
2796 if (FrameIdx < 0)
2797 return;
2798
2800 MachineFrameInfo &MFI = MF.getFrameInfo();
2801
2802 if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2803 return;
2804
2805 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2806 FuncInfo->setHasNonRISpills();
2807}
2808
2809/// Returns true if the address N can be represented by a base register plus
2810/// a signed 16-bit displacement [r+imm], and if it is not better
2811/// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept
2812/// displacements that are multiples of that value.
2814 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2815 MaybeAlign EncodingAlignment) const {
2816 // FIXME dl should come from parent load or store, not from address
2817 SDLoc dl(N);
2818
2819 // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2820 // a [pc+imm].
2822 return false;
2823
2824 // If this can be more profitably realized as r+r, fail.
2825 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2826 return false;
2827
2828 if (N.getOpcode() == ISD::ADD) {
2829 int16_t imm = 0;
2830 if (isIntS16Immediate(N.getOperand(1), imm) &&
2831 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2832 Disp = DAG.getSignedTargetConstant(imm, dl, N.getValueType());
2833 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2834 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2835 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2836 } else {
2837 Base = N.getOperand(0);
2838 }
2839 return true; // [r+i]
2840 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2841 // Match LOAD (ADD (X, Lo(G))).
2842 assert(!N.getOperand(1).getConstantOperandVal(1) &&
2843 "Cannot handle constant offsets yet!");
2844 Disp = N.getOperand(1).getOperand(0); // The global address.
2849 Base = N.getOperand(0);
2850 return true; // [&g+r]
2851 }
2852 } else if (N.getOpcode() == ISD::OR) {
2853 int16_t imm = 0;
2854 if (isIntS16Immediate(N.getOperand(1), imm) &&
2855 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2856 // If this is an or of disjoint bitfields, we can codegen this as an add
2857 // (for better address arithmetic) if the LHS and RHS of the OR are
2858 // provably disjoint.
2859 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2860
2861 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2862 // If all of the bits are known zero on the LHS or RHS, the add won't
2863 // carry.
2864 if (FrameIndexSDNode *FI =
2865 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2866 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2867 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2868 } else {
2869 Base = N.getOperand(0);
2870 }
2871 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2872 return true;
2873 }
2874 }
2875 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2876 // Loading from a constant address.
2877
2878 // If this address fits entirely in a 16-bit sext immediate field, codegen
2879 // this as "d, 0"
2880 int16_t Imm;
2881 if (isIntS16Immediate(CN, Imm) &&
2882 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2883 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2884 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2885 CN->getValueType(0));
2886 return true;
2887 }
2888
2889 // Handle 32-bit sext immediates with LIS + addr mode.
2890 if ((CN->getValueType(0) == MVT::i32 ||
2891 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2892 (!EncodingAlignment ||
2893 isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2894 int Addr = (int)CN->getZExtValue();
2895
2896 // Otherwise, break this down into an LIS + disp.
2897 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2898
2899 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2900 MVT::i32);
2901 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2902 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2903 return true;
2904 }
2905 }
2906
2907 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2908 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2909 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2910 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2911 } else
2912 Base = N;
2913 return true; // [r+0]
2914}
2915
2916/// Similar to the 16-bit case but for instructions that take a 34-bit
2917/// displacement field (prefixed loads/stores).
2919 SDValue &Base,
2920 SelectionDAG &DAG) const {
2921 // Only on 64-bit targets.
2922 if (N.getValueType() != MVT::i64)
2923 return false;
2924
2925 SDLoc dl(N);
2926 int64_t Imm = 0;
2927
2928 if (N.getOpcode() == ISD::ADD) {
2929 if (!isIntS34Immediate(N.getOperand(1), Imm))
2930 return false;
2931 Disp = DAG.getSignedTargetConstant(Imm, dl, N.getValueType());
2932 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2933 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2934 else
2935 Base = N.getOperand(0);
2936 return true;
2937 }
2938
2939 if (N.getOpcode() == ISD::OR) {
2940 if (!isIntS34Immediate(N.getOperand(1), Imm))
2941 return false;
2942 // If this is an or of disjoint bitfields, we can codegen this as an add
2943 // (for better address arithmetic) if the LHS and RHS of the OR are
2944 // provably disjoint.
2945 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2946 if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2947 return false;
2948 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2949 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2950 else
2951 Base = N.getOperand(0);
2952 Disp = DAG.getSignedTargetConstant(Imm, dl, N.getValueType());
2953 return true;
2954 }
2955
2956 if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2957 Disp = DAG.getSignedTargetConstant(Imm, dl, N.getValueType());
2958 Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2959 return true;
2960 }
2961
2962 return false;
2963}
2964
2965/// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2966/// represented as an indexed [r+r] operation.
2968 SDValue &Index,
2969 SelectionDAG &DAG) const {
2970 // Check to see if we can easily represent this as an [r+r] address. This
2971 // will fail if it thinks that the address is more profitably represented as
2972 // reg+imm, e.g. where imm = 0.
2973 if (SelectAddressRegReg(N, Base, Index, DAG))
2974 return true;
2975
2976 // If the address is the result of an add, we will utilize the fact that the
2977 // address calculation includes an implicit add. However, we can reduce
2978 // register pressure if we do not materialize a constant just for use as the
2979 // index register. We only get rid of the add if it is not an add of a
2980 // value and a 16-bit signed constant and both have a single use.
2981 int16_t imm = 0;
2982 if (N.getOpcode() == ISD::ADD &&
2983 (!isIntS16Immediate(N.getOperand(1), imm) ||
2984 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2985 Base = N.getOperand(0);
2986 Index = N.getOperand(1);
2987 return true;
2988 }
2989
2990 // Otherwise, do it the hard way, using R0 as the base register.
2991 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2992 N.getValueType());
2993 Index = N;
2994 return true;
2995}
2996
2997template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2998 Ty *PCRelCand = dyn_cast<Ty>(N);
2999 return PCRelCand && (PPCInstrInfo::hasPCRelFlag(PCRelCand->getTargetFlags()));
3000}
3001
3002/// Returns true if this address is a PC Relative address.
3003/// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
3004/// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
3006 // This is a materialize PC Relative node. Always select this as PC Relative.
3007 Base = N;
3008 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
3009 return true;
3010 if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
3011 isValidPCRelNode<GlobalAddressSDNode>(N) ||
3012 isValidPCRelNode<JumpTableSDNode>(N) ||
3013 isValidPCRelNode<BlockAddressSDNode>(N))
3014 return true;
3015 return false;
3016}
3017
3018/// Returns true if we should use a direct load into vector instruction
3019/// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
3020static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
3021
3022 // If there are any other uses other than scalar to vector, then we should
3023 // keep it as a scalar load -> direct move pattern to prevent multiple
3024 // loads.
3025 LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
3026 if (!LD)
3027 return false;
3028
3029 EVT MemVT = LD->getMemoryVT();
3030 if (!MemVT.isSimple())
3031 return false;
3032 switch(MemVT.getSimpleVT().SimpleTy) {
3033 case MVT::i64:
3034 break;
3035 case MVT::i32:
3036 if (!ST.hasP8Vector())
3037 return false;
3038 break;
3039 case MVT::i16:
3040 case MVT::i8:
3041 if (!ST.hasP9Vector())
3042 return false;
3043 break;
3044 default:
3045 return false;
3046 }
3047
3048 SDValue LoadedVal(N, 0);
3049 if (!LoadedVal.hasOneUse())
3050 return false;
3051
3052 for (SDUse &Use : LD->uses())
3053 if (Use.getResNo() == 0 &&
3054 Use.getUser()->getOpcode() != ISD::SCALAR_TO_VECTOR &&
3056 return false;
3057
3058 return true;
3059}
3060
3061/// getPreIndexedAddressParts - returns true by value, base pointer and
3062/// offset pointer and addressing mode by reference if the node's address
3063/// can be legally represented as pre-indexed load / store address.
3065 SDValue &Offset,
3067 SelectionDAG &DAG) const {
3068 if (DisablePPCPreinc) return false;
3069
3070 bool isLoad = true;
3071 SDValue Ptr;
3072 EVT VT;
3073 Align Alignment;
3074 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3075 Ptr = LD->getBasePtr();
3076 VT = LD->getMemoryVT();
3077 Alignment = LD->getAlign();
3078 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3079 Ptr = ST->getBasePtr();
3080 VT = ST->getMemoryVT();
3081 Alignment = ST->getAlign();
3082 isLoad = false;
3083 } else
3084 return false;
3085
3086 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
3087 // instructions because we can fold these into a more efficient instruction
3088 // instead, (such as LXSD).
3089 if (isLoad && usePartialVectorLoads(N, Subtarget)) {
3090 return false;
3091 }
3092
3093 // PowerPC doesn't have preinc load/store instructions for vectors
3094 if (VT.isVector())
3095 return false;
3096
3097 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
3098 // Common code will reject creating a pre-inc form if the base pointer
3099 // is a frame index, or if N is a store and the base pointer is either
3100 // the same as or a predecessor of the value being stored. Check for
3101 // those situations here, and try with swapped Base/Offset instead.
3102 bool Swap = false;
3103
3104 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
3105 Swap = true;
3106 else if (!isLoad) {
3107 SDValue Val = cast<StoreSDNode>(N)->getValue();
3108 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
3109 Swap = true;
3110 }
3111
3112 if (Swap)
3114
3115 AM = ISD::PRE_INC;
3116 return true;
3117 }
3118
3119 // LDU/STU can only handle immediates that are a multiple of 4.
3120 if (VT != MVT::i64) {
3121 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, std::nullopt))
3122 return false;
3123 } else {
3124 // LDU/STU need an address with at least 4-byte alignment.
3125 if (Alignment < Align(4))
3126 return false;
3127
3128 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
3129 return false;
3130 }
3131
3132 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3133 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
3134 // sext i32 to i64 when addr mode is r+i.
3135 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
3136 LD->getExtensionType() == ISD::SEXTLOAD &&
3137 isa<ConstantSDNode>(Offset))
3138 return false;
3139 }
3140
3141 AM = ISD::PRE_INC;
3142 return true;
3143}
3144
3145//===----------------------------------------------------------------------===//
3146// LowerOperation implementation
3147//===----------------------------------------------------------------------===//
3148
3149/// Return true if we should reference labels using a PICBase, set the HiOpFlags
3150/// and LoOpFlags to the target MO flags.
3151static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
3152 unsigned &HiOpFlags, unsigned &LoOpFlags,
3153 const GlobalValue *GV = nullptr) {
3154 HiOpFlags = PPCII::MO_HA;
3155 LoOpFlags = PPCII::MO_LO;
3156
3157 // Don't use the pic base if not in PIC relocation model.
3158 if (IsPIC) {
3159 HiOpFlags = PPCII::MO_PIC_HA_FLAG;
3160 LoOpFlags = PPCII::MO_PIC_LO_FLAG;
3161 }
3162}
3163
3164static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
3165 SelectionDAG &DAG) {
3166 SDLoc DL(HiPart);
3167 EVT PtrVT = HiPart.getValueType();
3168 SDValue Zero = DAG.getConstant(0, DL, PtrVT);
3169
3170 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
3171 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
3172
3173 // With PIC, the first instruction is actually "GR+hi(&G)".
3174 if (isPIC)
3175 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
3176 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
3177
3178 // Generate non-pic code that has direct accesses to the constant pool.
3179 // The address of the global is just (hi(&g)+lo(&g)).
3180 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
3181}
3182
3184 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3185 FuncInfo->setUsesTOCBasePtr();
3186}
3187
3190}
3191
3192SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
3193 SDValue GA) const {
3194 EVT VT = Subtarget.getScalarIntVT();
3195 SDValue Reg = Subtarget.isPPC64() ? DAG.getRegister(PPC::X2, VT)
3196 : Subtarget.isAIXABI()
3197 ? DAG.getRegister(PPC::R2, VT)
3198 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
3199 SDValue Ops[] = { GA, Reg };
3200 return DAG.getMemIntrinsicNode(
3201 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
3204}
3205
3206SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
3207 SelectionDAG &DAG) const {
3208 EVT PtrVT = Op.getValueType();
3209 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3210 const Constant *C = CP->getConstVal();
3211
3212 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3213 // The actual address of the GlobalValue is stored in the TOC.
3214 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3215 if (Subtarget.isUsingPCRelativeCalls()) {
3216 SDLoc DL(CP);
3217 EVT Ty = getPointerTy(DAG.getDataLayout());
3218 SDValue ConstPool = DAG.getTargetConstantPool(
3219 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
3220 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
3221 }
3222 setUsesTOCBasePtr(DAG);
3223 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
3224 return getTOCEntry(DAG, SDLoc(CP), GA);
3225 }
3226
3227 unsigned MOHiFlag, MOLoFlag;
3228 bool IsPIC = isPositionIndependent();
3229 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3230
3231 if (IsPIC && Subtarget.isSVR4ABI()) {
3232 SDValue GA =
3233 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
3234 return getTOCEntry(DAG, SDLoc(CP), GA);
3235 }
3236
3237 SDValue CPIHi =
3238 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
3239 SDValue CPILo =
3240 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
3241 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
3242}
3243
3244// For 64-bit PowerPC, prefer the more compact relative encodings.
3245// This trades 32 bits per jump table entry for one or two instructions
3246// on the jump site.
3248 if (isJumpTableRelative())
3250
3252}
3253
3256 return false;
3257 if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3258 return true;
3260}
3261
3263 SelectionDAG &DAG) const {
3264 if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3266
3267 switch (getTargetMachine().getCodeModel()) {
3268 case CodeModel::Small:
3269 case CodeModel::Medium:
3271 default:
3272 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3274 }
3275}
3276
3277const MCExpr *
3279 unsigned JTI,
3280 MCContext &Ctx) const {
3281 if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3283
3284 switch (getTargetMachine().getCodeModel()) {
3285 case CodeModel::Small:
3286 case CodeModel::Medium:
3288 default:
3289 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3290 }
3291}
3292
3293SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3294 EVT PtrVT = Op.getValueType();
3295 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3296
3297 // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3298 if (Subtarget.isUsingPCRelativeCalls()) {
3299 SDLoc DL(JT);
3300 EVT Ty = getPointerTy(DAG.getDataLayout());
3301 SDValue GA =
3302 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
3303 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3304 return MatAddr;
3305 }
3306
3307 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3308 // The actual address of the GlobalValue is stored in the TOC.
3309 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3310 setUsesTOCBasePtr(DAG);
3311 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3312 return getTOCEntry(DAG, SDLoc(JT), GA);
3313 }
3314
3315 unsigned MOHiFlag, MOLoFlag;
3316 bool IsPIC = isPositionIndependent();
3317 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3318
3319 if (IsPIC && Subtarget.isSVR4ABI()) {
3320 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3322 return getTOCEntry(DAG, SDLoc(GA), GA);
3323 }
3324
3325 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3326 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3327 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3328}
3329
3330SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3331 SelectionDAG &DAG) const {
3332 EVT PtrVT = Op.getValueType();
3333 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3334 const BlockAddress *BA = BASDN->getBlockAddress();
3335
3336 // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3337 if (Subtarget.isUsingPCRelativeCalls()) {
3338 SDLoc DL(BASDN);
3339 EVT Ty = getPointerTy(DAG.getDataLayout());
3340 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3342 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3343 return MatAddr;
3344 }
3345
3346 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3347 // The actual BlockAddress is stored in the TOC.
3348 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3349 setUsesTOCBasePtr(DAG);
3350 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3351 return getTOCEntry(DAG, SDLoc(BASDN), GA);
3352 }
3353
3354 // 32-bit position-independent ELF stores the BlockAddress in the .got.
3355 if (Subtarget.is32BitELFABI() && isPositionIndependent())
3356 return getTOCEntry(
3357 DAG, SDLoc(BASDN),
3358 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3359
3360 unsigned MOHiFlag, MOLoFlag;
3361 bool IsPIC = isPositionIndependent();
3362 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3363 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3364 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3365 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3366}
3367
3368SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3369 SelectionDAG &DAG) const {
3370 if (Subtarget.isAIXABI())
3371 return LowerGlobalTLSAddressAIX(Op, DAG);
3372
3373 return LowerGlobalTLSAddressLinux(Op, DAG);
3374}
3375
3376/// updateForAIXShLibTLSModelOpt - Helper to initialize TLS model opt settings,
3377/// and then apply the update.
3379 SelectionDAG &DAG,
3380 const TargetMachine &TM) {
3381 // Initialize TLS model opt setting lazily:
3382 // (1) Use initial-exec for single TLS var references within current function.
3383 // (2) Use local-dynamic for multiple TLS var references within current
3384 // function.
3385 PPCFunctionInfo *FuncInfo =
3387 if (!FuncInfo->isAIXFuncTLSModelOptInitDone()) {
3389 // Iterate over all instructions within current function, collect all TLS
3390 // global variables (global variables taken as the first parameter to
3391 // Intrinsic::threadlocal_address).
3392 const Function &Func = DAG.getMachineFunction().getFunction();
3393 for (const BasicBlock &BB : Func)
3394 for (const Instruction &I : BB)
3395 if (I.getOpcode() == Instruction::Call)
3396 if (const CallInst *CI = dyn_cast<const CallInst>(&I))
3397 if (Function *CF = CI->getCalledFunction())
3398 if (CF->isDeclaration() &&
3399 CF->getIntrinsicID() == Intrinsic::threadlocal_address)
3400 if (const GlobalValue *GV =
3401 dyn_cast<GlobalValue>(I.getOperand(0))) {
3402 TLSModel::Model GVModel = TM.getTLSModel(GV);
3403 if (GVModel == TLSModel::LocalDynamic)
3404 TLSGV.insert(GV);
3405 }
3406
3407 unsigned TLSGVCnt = TLSGV.size();
3408 LLVM_DEBUG(dbgs() << format("LocalDynamic TLSGV count:%d\n", TLSGVCnt));
3409 if (TLSGVCnt <= PPCAIXTLSModelOptUseIEForLDLimit)
3410 FuncInfo->setAIXFuncUseTLSIEForLD();
3412 }
3413
3414 if (FuncInfo->isAIXFuncUseTLSIEForLD()) {
3415 LLVM_DEBUG(
3416 dbgs() << DAG.getMachineFunction().getName()
3417 << " function is using the TLS-IE model for TLS-LD access.\n");
3418 Model = TLSModel::InitialExec;
3419 }
3420}
3421
3422SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
3423 SelectionDAG &DAG) const {
3424 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3425
3426 if (DAG.getTarget().useEmulatedTLS())
3427 report_fatal_error("Emulated TLS is not yet supported on AIX");
3428
3429 SDLoc dl(GA);
3430 const GlobalValue *GV = GA->getGlobal();
3431 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3432 bool Is64Bit = Subtarget.isPPC64();
3434
3435 // Apply update to the TLS model.
3436 if (Subtarget.hasAIXShLibTLSModelOpt())
3438
3439 // TLS variables are accessed through TOC entries.
3440 // To support this, set the DAG to use the TOC base pointer.
3441 setUsesTOCBasePtr(DAG);
3442
3443 bool IsTLSLocalExecModel = Model == TLSModel::LocalExec;
3444
3445 if (IsTLSLocalExecModel || Model == TLSModel::InitialExec) {
3446 bool HasAIXSmallLocalExecTLS = Subtarget.hasAIXSmallLocalExecTLS();
3447 bool HasAIXSmallTLSGlobalAttr = false;
3448 SDValue VariableOffsetTGA =
3449 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TPREL_FLAG);
3450 SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3451 SDValue TLSReg;
3452
3453 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
3454 if (GVar->hasAttribute("aix-small-tls"))
3455 HasAIXSmallTLSGlobalAttr = true;
3456
3457 if (Is64Bit) {
3458 // For local-exec and initial-exec on AIX (64-bit), the sequence generated
3459 // involves a load of the variable offset (from the TOC), followed by an
3460 // add of the loaded variable offset to R13 (the thread pointer).
3461 // This code sequence looks like:
3462 // ld reg1,var[TC](2)
3463 // add reg2, reg1, r13 // r13 contains the thread pointer
3464 TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3465
3466 // With the -maix-small-local-exec-tls option, or with the "aix-small-tls"
3467 // global variable attribute, produce a faster access sequence for
3468 // local-exec TLS variables where the offset from the TLS base is encoded
3469 // as an immediate operand.
3470 //
3471 // We only utilize the faster local-exec access sequence when the TLS
3472 // variable has a size within the policy limit. We treat types that are
3473 // not sized or are empty as being over the policy size limit.
3474 if ((HasAIXSmallLocalExecTLS || HasAIXSmallTLSGlobalAttr) &&
3475 IsTLSLocalExecModel) {
3476 Type *GVType = GV->getValueType();
3477 if (GVType->isSized() && !GVType->isEmptyTy() &&
3478 GV->getDataLayout().getTypeAllocSize(GVType) <=
3480 return DAG.getNode(PPCISD::Lo, dl, PtrVT, VariableOffsetTGA, TLSReg);
3481 }
3482 } else {
3483 // For local-exec and initial-exec on AIX (32-bit), the sequence generated
3484 // involves loading the variable offset from the TOC, generating a call to
3485 // .__get_tpointer to get the thread pointer (which will be in R3), and
3486 // adding the two together:
3487 // lwz reg1,var[TC](2)
3488 // bla .__get_tpointer
3489 // add reg2, reg1, r3
3490 TLSReg = DAG.getNode(PPCISD::GET_TPOINTER, dl, PtrVT);
3491
3492 // We do not implement the 32-bit version of the faster access sequence
3493 // for local-exec that is controlled by the -maix-small-local-exec-tls
3494 // option, or the "aix-small-tls" global variable attribute.
3495 if (HasAIXSmallLocalExecTLS || HasAIXSmallTLSGlobalAttr)
3496 report_fatal_error("The small-local-exec TLS access sequence is "
3497 "currently only supported on AIX (64-bit mode).");
3498 }
3499 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, VariableOffset);
3500 }
3501
3502 if (Model == TLSModel::LocalDynamic) {
3503 bool HasAIXSmallLocalDynamicTLS = Subtarget.hasAIXSmallLocalDynamicTLS();
3504
3505 // We do not implement the 32-bit version of the faster access sequence
3506 // for local-dynamic that is controlled by -maix-small-local-dynamic-tls.
3507 if (!Is64Bit && HasAIXSmallLocalDynamicTLS)
3508 report_fatal_error("The small-local-dynamic TLS access sequence is "
3509 "currently only supported on AIX (64-bit mode).");
3510
3511 // For local-dynamic on AIX, we need to generate one TOC entry for each
3512 // variable offset, and a single module-handle TOC entry for the entire
3513 // file.
3514
3515 SDValue VariableOffsetTGA =
3516 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSLD_FLAG);
3517 SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3518
3520 GlobalVariable *TLSGV =
3521 dyn_cast_or_null<GlobalVariable>(M->getOrInsertGlobal(
3522 StringRef("_$TLSML"), PointerType::getUnqual(*DAG.getContext())));
3524 assert(TLSGV && "Not able to create GV for _$TLSML.");
3525 SDValue ModuleHandleTGA =
3526 DAG.getTargetGlobalAddress(TLSGV, dl, PtrVT, 0, PPCII::MO_TLSLDM_FLAG);
3527 SDValue ModuleHandleTOC = getTOCEntry(DAG, dl, ModuleHandleTGA);
3528 SDValue ModuleHandle =
3529 DAG.getNode(PPCISD::TLSLD_AIX, dl, PtrVT, ModuleHandleTOC);
3530
3531 // With the -maix-small-local-dynamic-tls option, produce a faster access
3532 // sequence for local-dynamic TLS variables where the offset from the
3533 // module-handle is encoded as an immediate operand.
3534 //
3535 // We only utilize the faster local-dynamic access sequence when the TLS
3536 // variable has a size within the policy limit. We treat types that are
3537 // not sized or are empty as being over the policy size limit.
3538 if (HasAIXSmallLocalDynamicTLS) {
3539 Type *GVType = GV->getValueType();
3540 if (GVType->isSized() && !GVType->isEmptyTy() &&
3541 GV->getDataLayout().getTypeAllocSize(GVType) <=
3543 return DAG.getNode(PPCISD::Lo, dl, PtrVT, VariableOffsetTGA,
3544 ModuleHandle);
3545 }
3546
3547 return DAG.getNode(ISD::ADD, dl, PtrVT, ModuleHandle, VariableOffset);
3548 }
3549
3550 // If Local- or Initial-exec or Local-dynamic is not possible or specified,
3551 // all GlobalTLSAddress nodes are lowered using the general-dynamic model. We
3552 // need to generate two TOC entries, one for the variable offset, one for the
3553 // region handle. The global address for the TOC entry of the region handle is
3554 // created with the MO_TLSGDM_FLAG flag and the global address for the TOC
3555 // entry of the variable offset is created with MO_TLSGD_FLAG.
3556 SDValue VariableOffsetTGA =
3557 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG);
3558 SDValue RegionHandleTGA =
3559 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG);
3560 SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3561 SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA);
3562 return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset,
3563 RegionHandle);
3564}
3565
3566SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op,
3567 SelectionDAG &DAG) const {
3568 // FIXME: TLS addresses currently use medium model code sequences,
3569 // which is the most useful form. Eventually support for small and
3570 // large models could be added if users need it, at the cost of
3571 // additional complexity.
3572 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3573 if (DAG.getTarget().useEmulatedTLS())
3574 return LowerToTLSEmulatedModel(GA, DAG);
3575
3576 SDLoc dl(GA);
3577 const GlobalValue *GV = GA->getGlobal();
3578 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3579 bool is64bit = Subtarget.isPPC64();
3580 const Module *M = DAG.getMachineFunction().getFunction().getParent();
3581 PICLevel::Level picLevel = M->getPICLevel();
3582
3584 TLSModel::Model Model = TM.getTLSModel(GV);
3585
3586 if (Model == TLSModel::LocalExec) {
3587 if (Subtarget.isUsingPCRelativeCalls()) {
3588 SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3589 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3591 SDValue MatAddr =
3592 DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3593 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3594 }
3595
3596 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3598 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3600 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3601 : DAG.getRegister(PPC::R2, MVT::i32);
3602
3603 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3604 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3605 }
3606
3607 if (Model == TLSModel::InitialExec) {
3608 bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3610 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3611 SDValue TGATLS = DAG.getTargetGlobalAddress(
3612 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_TLS_PCREL_FLAG : PPCII::MO_TLS);
3613 SDValue TPOffset;
3614 if (IsPCRel) {
3615 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3616 TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3618 } else {
3619 SDValue GOTPtr;
3620 if (is64bit) {
3621 setUsesTOCBasePtr(DAG);
3622 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3623 GOTPtr =
3624 DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3625 } else {
3626 if (!TM.isPositionIndependent())
3627 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3628 else if (picLevel == PICLevel::SmallPIC)
3629 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3630 else
3631 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3632 }
3633 TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3634 }
3635 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3636 }
3637
3638 if (Model == TLSModel::GeneralDynamic) {
3639 if (Subtarget.isUsingPCRelativeCalls()) {
3640 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3642 return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3643 }
3644
3645 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3646 SDValue GOTPtr;
3647 if (is64bit) {
3648 setUsesTOCBasePtr(DAG);
3649 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3650 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3651 GOTReg, TGA);
3652 } else {
3653 if (picLevel == PICLevel::SmallPIC)
3654 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3655 else
3656 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3657 }
3658 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3659 GOTPtr, TGA, TGA);
3660 }
3661
3662 if (Model == TLSModel::LocalDynamic) {
3663 if (Subtarget.isUsingPCRelativeCalls()) {
3664 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3666 SDValue MatPCRel =
3667 DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3668 return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3669 }
3670
3671 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3672 SDValue GOTPtr;
3673 if (is64bit) {
3674 setUsesTOCBasePtr(DAG);
3675 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3676 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3677 GOTReg, TGA);
3678 } else {
3679 if (picLevel == PICLevel::SmallPIC)
3680 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3681 else
3682 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3683 }
3684 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3685 PtrVT, GOTPtr, TGA, TGA);
3686 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3687 PtrVT, TLSAddr, TGA);
3688 return DAG.