LLVM 24.0.0git
ARMISelLowering.cpp
Go to the documentation of this file.
1//===- ARMISelLowering.cpp - ARM 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 defines the interfaces that ARM uses to lower LLVM code into a
10// selection DAG.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ARMISelLowering.h"
15#include "ARMBaseInstrInfo.h"
16#include "ARMBaseRegisterInfo.h"
17#include "ARMCallingConv.h"
20#include "ARMPerfectShuffle.h"
21#include "ARMRegisterInfo.h"
22#include "ARMSelectionDAGInfo.h"
23#include "ARMSubtarget.h"
27#include "Utils/ARMBaseInfo.h"
28#include "llvm/ADT/APFloat.h"
29#include "llvm/ADT/APInt.h"
30#include "llvm/ADT/ArrayRef.h"
31#include "llvm/ADT/BitVector.h"
32#include "llvm/ADT/DenseMap.h"
33#include "llvm/ADT/STLExtras.h"
36#include "llvm/ADT/Statistic.h"
38#include "llvm/ADT/StringRef.h"
40#include "llvm/ADT/Twine.h"
67#include "llvm/IR/Attributes.h"
68#include "llvm/IR/CallingConv.h"
69#include "llvm/IR/Constant.h"
70#include "llvm/IR/Constants.h"
71#include "llvm/IR/DataLayout.h"
72#include "llvm/IR/DebugLoc.h"
74#include "llvm/IR/Function.h"
75#include "llvm/IR/GlobalAlias.h"
76#include "llvm/IR/GlobalValue.h"
78#include "llvm/IR/IRBuilder.h"
79#include "llvm/IR/InlineAsm.h"
80#include "llvm/IR/Instruction.h"
83#include "llvm/IR/Intrinsics.h"
84#include "llvm/IR/IntrinsicsARM.h"
85#include "llvm/IR/Module.h"
86#include "llvm/IR/Type.h"
87#include "llvm/IR/User.h"
88#include "llvm/IR/Value.h"
89#include "llvm/MC/MCInstrDesc.h"
91#include "llvm/MC/MCSchedule.h"
98#include "llvm/Support/Debug.h"
106#include <algorithm>
107#include <cassert>
108#include <cstdint>
109#include <iterator>
110#include <limits>
111#include <optional>
112#include <tuple>
113#include <utility>
114#include <vector>
115
116using namespace llvm;
117using namespace llvm::SDPatternMatch;
118
119#define DEBUG_TYPE "arm-isel"
120
121STATISTIC(NumTailCalls, "Number of tail calls");
122STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
123STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
124STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
125STATISTIC(NumConstpoolPromoted,
126 "Number of constants with their storage promoted into constant pools");
127
128static cl::opt<bool>
129ARMInterworking("arm-interworking", cl::Hidden,
130 cl::desc("Enable / disable ARM interworking (for debugging only)"),
131 cl::init(true));
132
134 "arm-promote-constant", cl::Hidden,
135 cl::desc("Enable / disable promotion of unnamed_addr constants into "
136 "constant pools"),
137 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
139 "arm-promote-constant-max-size", cl::Hidden,
140 cl::desc("Maximum size of constant to promote into a constant pool"),
141 cl::init(64));
143 "arm-promote-constant-max-total", cl::Hidden,
144 cl::desc("Maximum size of ALL constants to promote into a constant pool"),
145 cl::init(128));
146
148MVEMaxSupportedInterleaveFactor("mve-max-interleave-factor", cl::Hidden,
149 cl::desc("Maximum interleave factor for MVE VLDn to generate."),
150 cl::init(2));
151
153 "arm-max-base-updates-to-check", cl::Hidden,
154 cl::desc("Maximum number of base-updates to check generating postindex."),
155 cl::init(64));
156
157/// Value type used for "flags" operands / results (either CPSR or FPSCR_NZCV).
158constexpr MVT FlagsVT = MVT::i32;
159
160// The APCS parameter registers.
161static const MCPhysReg GPRArgRegs[] = {
162 ARM::R0, ARM::R1, ARM::R2, ARM::R3
163};
164
166 SelectionDAG &DAG, const SDLoc &DL) {
168 assert(Arg.ArgVT.bitsLT(MVT::i32));
170 SDValue Ext =
172 MVT::i32, Trunc);
173 return Ext;
174}
175
176void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT) {
177 if (VT != PromotedLdStVT) {
179 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
180
182 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
183 }
184
185 MVT ElemTy = VT.getVectorElementType();
186 if (ElemTy != MVT::f64)
190 if (ElemTy == MVT::i32) {
195 } else {
200 }
209 if (VT.isInteger()) {
213 }
214
215 // Neon does not support vector divide/remainder operations.
224
225 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
226 for (auto Opcode : {ISD::ABS, ISD::ABDS, ISD::ABDU, ISD::SMIN, ISD::SMAX,
228 setOperationAction(Opcode, VT, Legal);
229 if (!VT.isFloatingPoint())
230 for (auto Opcode : {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT})
231 setOperationAction(Opcode, VT, Legal);
232}
233
234void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
235 addRegisterClass(VT, &ARM::DPRRegClass);
236 addTypeForNEON(VT, MVT::f64);
237}
238
239void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
240 addRegisterClass(VT, &ARM::DPairRegClass);
241 addTypeForNEON(VT, MVT::v2f64);
242}
243
244void ARMTargetLowering::setAllExpand(MVT VT) {
245 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
247
248 // We support these really simple operations even on types where all
249 // the actual arithmetic has to be broken down into simpler
250 // operations or turned into library calls.
255}
256
257void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To,
258 LegalizeAction Action) {
259 setLoadExtAction(ISD::EXTLOAD, From, To, Action);
260 setLoadExtAction(ISD::ZEXTLOAD, From, To, Action);
261 setLoadExtAction(ISD::SEXTLOAD, From, To, Action);
262}
263
264void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) {
265 const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 };
266
267 for (auto VT : IntTypes) {
268 addRegisterClass(VT, &ARM::MQPRRegClass);
299
300 // No native support for these.
310
311 // Vector reductions
321
322 if (!HasMVEFP) {
327 } else {
330 }
331
332 // Pre and Post inc are supported on loads and stores
333 for (unsigned im = (unsigned)ISD::PRE_INC;
334 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
339 }
340 }
341
342 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
343 for (auto VT : FloatTypes) {
344 addRegisterClass(VT, &ARM::MQPRRegClass);
345 if (!HasMVEFP)
346 setAllExpand(VT);
347
348 // These are legal or custom whether we have MVE.fp or not
361
362 // Pre and Post inc are supported on loads and stores
363 for (unsigned im = (unsigned)ISD::PRE_INC;
364 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
369 }
370
371 if (HasMVEFP) {
374 for (auto Op :
379 }
384
385 // No native support for these.
400 }
401 }
402
403 // Custom Expand smaller than legal vector reductions to prevent false zero
404 // items being added.
413
414 // We 'support' these types up to bitcast/load/store level, regardless of
415 // MVE integer-only / float support. Only doing FP data processing on the FP
416 // vector types is inhibited at integer-only level.
417 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
418 for (auto VT : LongTypes) {
419 addRegisterClass(VT, &ARM::MQPRRegClass);
420 setAllExpand(VT);
426 }
428
429 // We can do bitwise operations on v2i64 vectors
430 setOperationAction(ISD::AND, MVT::v2i64, Legal);
431 setOperationAction(ISD::OR, MVT::v2i64, Legal);
432 setOperationAction(ISD::XOR, MVT::v2i64, Legal);
433
434 // It is legal to extload from v4i8 to v4i16 or v4i32.
435 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
436 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
437 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
438
439 // It is legal to sign extend from v4i8/v4i16 to v4i32 or v8i8 to v8i16.
445
446 // Some truncating stores are legal too.
447 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
448 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
449 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
450
451 // Pre and Post inc on these are legal, given the correct extends
452 for (unsigned im = (unsigned)ISD::PRE_INC;
453 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
454 for (auto VT : {MVT::v8i8, MVT::v4i8, MVT::v4i16}) {
459 }
460 }
461
462 // Predicate types
463 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1, MVT::v2i1};
464 for (auto VT : pTypes) {
465 addRegisterClass(VT, &ARM::VCCRRegClass);
480
481 if (!HasMVEFP) {
486 }
487 }
491 setOperationAction(ISD::OR, MVT::v2i1, Expand);
497
506}
507
508static bool hasNativeAtomics(const ARMSubtarget &ST) {
509 return ST.hasAnyDataBarrier() && (!ST.isThumb() || ST.hasV8MBaselineOps());
510}
511
513 return static_cast<const ARMBaseTargetMachine &>(getTargetMachine());
514}
515
517 const ARMSubtarget &STI)
518 : TargetLowering(TM_, STI), Subtarget(&STI),
519 RegInfo(Subtarget->getRegisterInfo()),
520 Itins(Subtarget->getInstrItineraryData()) {
521 const auto &TM = static_cast<const ARMBaseTargetMachine &>(TM_);
522
525
526 const Triple &TT = TM.getTargetTriple();
527
528 if (Subtarget->isThumb1Only())
529 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
530 else
531 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
532
533 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
534 Subtarget->hasFPRegs()) {
535 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
536 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
537
538 if (!Subtarget->hasVFP2Base()) {
539 setAllExpand(MVT::f32);
540 } else {
543
546 setOperationAction(Op, MVT::f32, Legal);
547 }
548 if (!Subtarget->hasFP64()) {
549 setAllExpand(MVT::f64);
550 } else {
553 setOperationAction(Op, MVT::f64, Legal);
554
556 }
557 }
558
559 if (Subtarget->hasFullFP16()) {
562 setOperationAction(Op, MVT::f16, Legal);
563
564 addRegisterClass(MVT::f16, &ARM::HPRRegClass);
567
572 }
573
574 if (Subtarget->hasBF16()) {
575 addRegisterClass(MVT::bf16, &ARM::HPRRegClass);
576 setAllExpand(MVT::bf16);
577 if (!Subtarget->hasFullFP16()) {
581 }
586
590 setOperationAction(Op, MVT::bf16, Promote);
591
592 for (auto Op : {ISD::FREM, ISD::FPOW, ISD::FPOWI,
606 setOperationAction(Op, MVT::bf16, Promote);
607 } else {
612 }
613
615 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
616 setTruncStoreAction(VT, InnerVT, Expand);
617 addAllExtLoads(VT, InnerVT, Expand);
618 }
619
622
624 }
625
626 if (!Subtarget->isThumb1Only() && !Subtarget->hasV8_1MMainlineOps())
628
629 if (!Subtarget->hasV8_1MMainlineOps())
631
632 if (!Subtarget->isThumb1Only())
634
637
640
641 if (Subtarget->hasMVEIntegerOps())
642 addMVEVectorTypes(Subtarget->hasMVEFloatOps());
643
644 // Combine low-overhead loop intrinsics so that we can lower i1 types.
645 if (Subtarget->hasLOB()) {
647 }
648
649 if (Subtarget->hasNEON()) {
650 addDRTypeForNEON(MVT::v2f32);
651 addDRTypeForNEON(MVT::v8i8);
652 addDRTypeForNEON(MVT::v4i16);
653 addDRTypeForNEON(MVT::v2i32);
654 addDRTypeForNEON(MVT::v1i64);
655
656 addQRTypeForNEON(MVT::v4f32);
657 addQRTypeForNEON(MVT::v2f64);
658 addQRTypeForNEON(MVT::v16i8);
659 addQRTypeForNEON(MVT::v8i16);
660 addQRTypeForNEON(MVT::v4i32);
661 addQRTypeForNEON(MVT::v2i64);
662
663 if (Subtarget->hasFullFP16()) {
664 addQRTypeForNEON(MVT::v8f16);
665 addDRTypeForNEON(MVT::v4f16);
666 }
667
668 if (Subtarget->hasBF16()) {
669 addQRTypeForNEON(MVT::v8bf16);
670 addDRTypeForNEON(MVT::v4bf16);
671 }
672 }
673
674 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
675 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
676 // none of Neon, MVE or VFP supports any arithmetic operations on it.
677 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
678 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
679 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
680 // FIXME: Code duplication: FDIV and FREM are expanded always, see
681 // ARMTargetLowering::addTypeForNEON method for details.
682 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
683 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
684 // FIXME: Create unittest.
685 // In another words, find a way when "copysign" appears in DAG with vector
686 // operands.
688 // FIXME: Code duplication: SETCC has custom operation action, see
689 // ARMTargetLowering::addTypeForNEON method for details.
691 // FIXME: Create unittest for FNEG and for FABS.
692 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
693 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
695 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
696 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
697 setOperationAction(ISD::FTAN, MVT::v2f64, Expand);
698 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
699 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
702 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
711 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
712 }
713
714 if (Subtarget->hasNEON()) {
715 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
716 // supported for v4f32.
718 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
719 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
720 setOperationAction(ISD::FTAN, MVT::v4f32, Expand);
721 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
722 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
725 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
734
735 // Mark v2f32 intrinsics.
737 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
738 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
739 setOperationAction(ISD::FTAN, MVT::v2f32, Expand);
740 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
741 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
744 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
753
756 setOperationAction(Op, MVT::v4f16, Expand);
757 setOperationAction(Op, MVT::v8f16, Expand);
758 }
759
760 // Neon does not support some operations on v1i64 and v2i64 types.
761 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
762 // Custom handling for some quad-vector types to detect VMULL.
763 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
764 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
765 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
766 // Custom handling for some vector types to avoid expensive expansions
767 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
769 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
771 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
772 // a destination type that is wider than the source, and nor does
773 // it have a FP_TO_[SU]INT instruction with a narrower destination than
774 // source.
783
786
787 // NEON does not have single instruction CTPOP for vectors with element
788 // types wider than 8-bits. However, custom lowering can leverage the
789 // v8i8/v16i8 vcnt instruction.
796
797 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
798 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
799
800 // NEON does not have single instruction CTTZ for vectors.
802 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
803 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
804 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
805
806 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
807 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
808 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
809 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
810
815
820
824 }
825
826 // NEON only has FMA instructions as of VFP4.
827 if (!Subtarget->hasVFP4Base()) {
828 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
829 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
830 }
831
834
835 // It is legal to extload from v4i8 to v4i16 or v4i32.
836 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
837 MVT::v2i32}) {
842 }
843 }
844
845 for (auto VT : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v16i8, MVT::v8i16,
846 MVT::v4i32}) {
851 }
852 }
853
854 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
861 }
862 if (Subtarget->hasMVEIntegerOps()) {
865 ISD::SETCC});
866 }
867 if (Subtarget->hasMVEFloatOps()) {
869 }
870
871 if (!Subtarget->hasFP64()) {
872 // When targeting a floating-point unit with only single-precision
873 // operations, f64 is legal for the few double-precision instructions which
874 // are present However, no double-precision operations other than moves,
875 // loads and stores are provided by the hardware.
912 }
913
914 // STRICT_(U/S)INT_TO_FP specifically use the input MVT to register with
915 // setOperationAction() as opposed to other opcodes that use the output MVT
916 // All inputs should be i32 due to type legalization
919
922
923 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
924 if (Subtarget->hasFullFP16()) {
927 }
928 }
929
930 if (Subtarget->hasFP16()) {
932 }
933
938
939 computeRegisterProperties(Subtarget->getRegisterInfo());
940
941 // ARM does not have floating-point extending loads.
942 for (MVT VT : MVT::fp_valuetypes()) {
943 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
944 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
945 setLoadExtAction(ISD::EXTLOAD, VT, MVT::bf16, Expand);
946 }
947
948 // ... or truncating stores
949 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
950 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
951 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
952 setTruncStoreAction(MVT::f32, MVT::bf16, Expand);
953 setTruncStoreAction(MVT::f64, MVT::bf16, Expand);
954
955 // ARM does not have i1 sign extending load.
956 for (MVT VT : MVT::integer_valuetypes())
958
959 // ARM supports all 4 flavors of integer indexed load / store.
960 if (!Subtarget->isThumb1Only()) {
961 for (unsigned im = (unsigned)ISD::PRE_INC;
963 setIndexedLoadAction(im, MVT::i1, Legal);
964 setIndexedLoadAction(im, MVT::i8, Legal);
965 setIndexedLoadAction(im, MVT::i16, Legal);
966 setIndexedLoadAction(im, MVT::i32, Legal);
967 setIndexedStoreAction(im, MVT::i1, Legal);
968 setIndexedStoreAction(im, MVT::i8, Legal);
969 setIndexedStoreAction(im, MVT::i16, Legal);
970 setIndexedStoreAction(im, MVT::i32, Legal);
971 }
972 } else {
973 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
976 }
977
978 // Custom loads/stores to possible use __aeabi_uread/write*
979 if (TT.isTargetAEABI() && !Subtarget->allowsUnalignedMem()) {
984 }
985
990
991 if (!Subtarget->isThumb1Only()) {
994 }
995
1000 if (Subtarget->hasDSP()) {
1009 }
1010 if (Subtarget->hasBaseDSP()) {
1013 }
1014
1015 // i64 operation support.
1018 if (Subtarget->isThumb1Only()) {
1021 }
1022 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
1023 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
1025
1035
1036 // MVE lowers 64 bit shifts to lsll and lsrl
1037 // assuming that ISD::SRL and SRA of i64 are already marked custom
1038 if (Subtarget->hasMVEIntegerOps())
1040
1041 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1042 if (Subtarget->isThumb1Only()) {
1046 }
1047
1048 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1050
1051 // ARM does not have ROTL.
1056 }
1058 // TODO: These two should be set to LibCall, but this currently breaks
1059 // the Linux kernel build. See #101786.
1062 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1065 }
1066
1067 // @llvm.readcyclecounter requires the Performance Monitors extension.
1068 // Default to the 0 expansion on unsupported platforms.
1069 // FIXME: Technically there are older ARM CPUs that have
1070 // implementation-specific ways of obtaining this information.
1071 if (Subtarget->hasPerfMon())
1073
1074 // Only ARMv6 has BSWAP.
1075 if (!Subtarget->hasV6Ops())
1077
1078 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1079 : Subtarget->hasDivideInARMMode();
1080 if (!hasDivide) {
1081 // These are expanded into libcalls if the cpu doesn't have HW divider.
1084 }
1085
1086 if (TT.isOSWindows() && !Subtarget->hasDivideInThumbMode()) {
1089
1092 }
1093
1096
1097 // Register based DivRem for AEABI (RTABI 4.2)
1098 if (TT.isTargetAEABI() || TT.isAndroid() || TT.isTargetGNUAEABI() ||
1099 TT.isTargetMuslAEABI() || TT.isOSFuchsia() || TT.isOSWindows()) {
1102 HasStandaloneRem = false;
1103
1108 } else {
1111 }
1112
1117
1118 setOperationAction(ISD::TRAP, MVT::Other, Legal);
1120
1121 // Use the default implementation.
1123 setOperationAction(ISD::VAARG, MVT::Other, Expand);
1125 setOperationAction(ISD::VAEND, MVT::Other, Expand);
1128
1129 if (TT.isOSWindows())
1131 else
1133
1134 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1135 // the default expansion.
1136 InsertFencesForAtomic = false;
1137 if (hasNativeAtomics(*Subtarget)) {
1138 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1139 // to ldrex/strex loops already.
1141 if (!Subtarget->isThumb() || !Subtarget->isMClass())
1143
1144 // On v8, we have particularly efficient implementations of atomic fences
1145 // if they can be combined with nearby atomic loads and stores.
1146 if (!Subtarget->hasAcquireRelease() ||
1147 getTargetMachine().getOptLevel() == CodeGenOptLevel::None) {
1148 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1149 InsertFencesForAtomic = true;
1150 }
1151 } else {
1152 // If there's anything we can use as a barrier, go through custom lowering
1153 // for ATOMIC_FENCE.
1154 // If target has DMB in thumb, Fences can be inserted.
1155 if (Subtarget->hasDataBarrier())
1156 InsertFencesForAtomic = true;
1157
1159 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1160
1161 // Set them all for libcall, which will force libcalls.
1167 {MVT::i8, MVT::i16, MVT::i32, MVT::i64}, LibCall);
1169 LibCall);
1170 }
1171
1172 // Compute supported atomic widths.
1173 if (TT.isOSLinux() || (!Subtarget->isMClass() && Subtarget->hasV6Ops())) {
1174 // For targets where __sync_* routines are reliably available, we use them
1175 // if necessary.
1176 //
1177 // ARM Linux always supports 64-bit atomics through kernel-assisted atomic
1178 // routines (kernel 3.1 or later). FIXME: Not with compiler-rt?
1179 //
1180 // ARMv6 targets have native instructions in ARM mode. For Thumb mode,
1181 // such targets should provide __sync_* routines, which use the ARM mode
1182 // instructions. (ARMv6 doesn't have dmb, but it has an equivalent
1183 // encoding; see ARMISD::MEMBARRIER_MCR.)
1185 } else if ((Subtarget->isMClass() && Subtarget->hasV8MBaselineOps()) ||
1186 Subtarget->hasForced32BitAtomics()) {
1187 // Cortex-M (besides Cortex-M0) have 32-bit atomics.
1189 } else {
1190 // We can't assume anything about other targets; just use libatomic
1191 // routines.
1193 }
1194
1196
1198
1199 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1200 if (!Subtarget->hasV6Ops()) {
1203 }
1205
1206 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1207 !Subtarget->isThumb1Only()) {
1208 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1209 // iff target supports vfp2.
1219 }
1220
1221 // We want to custom lower some of our intrinsics.
1226
1236 if (Subtarget->hasFullFP16()) {
1240 }
1241
1243
1246 if (Subtarget->hasFullFP16())
1250 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
1251
1252 // We don't support sin/cos/fmod/copysign/pow
1261 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1262 !Subtarget->isThumb1Only()) {
1265 }
1268
1269 if (!Subtarget->hasVFP4Base()) {
1272 }
1273
1274 // Various VFP goodness
1275 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1276 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1277 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1282 }
1283
1284 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1285 if (!Subtarget->hasFP16()) {
1290 }
1291
1292 // Strict floating-point comparisons need custom lowering.
1299 }
1300
1301 // FP-ARMv8 implements a lot of rounding-like FP operations.
1302 if (Subtarget->hasFPARMv8Base()) {
1303 for (auto Op :
1310 setOperationAction(Op, MVT::f32, Legal);
1311
1312 if (Subtarget->hasFP64())
1313 setOperationAction(Op, MVT::f64, Legal);
1314 }
1315
1316 if (Subtarget->hasNEON()) {
1321 }
1322 }
1323
1324 // FP16 often need to be promoted to call lib functions
1325 // clang-format off
1326 if (Subtarget->hasFullFP16()) {
1330
1331 for (auto Op : {ISD::FREM, ISD::FPOW, ISD::FPOWI,
1345 setOperationAction(Op, MVT::f16, Promote);
1346 }
1347
1348 // Round-to-integer need custom lowering for fp16, as Promote doesn't work
1349 // because the result type is integer.
1351 setOperationAction(Op, MVT::f16, Custom);
1352
1358 setOperationAction(Op, MVT::f16, Legal);
1359 }
1360 // clang-format on
1361 }
1362
1363 if (Subtarget->hasNEON()) {
1364 // vmin and vmax aren't available in a scalar form, so we can use
1365 // a NEON instruction with an undef lane instead.
1374
1375 if (Subtarget->hasV8Ops()) {
1376 for (auto Op :
1380 setOperationAction(Op, MVT::v2f32, Legal);
1381 setOperationAction(Op, MVT::v4f32, Legal);
1382 }
1383 }
1384
1385 if (Subtarget->hasFullFP16()) {
1390
1395
1396 for (auto Op :
1400 setOperationAction(Op, MVT::v4f16, Legal);
1401 setOperationAction(Op, MVT::v8f16, Legal);
1402 }
1403 }
1404 }
1405
1406 // On MSVC, both 32-bit and 64-bit, ldexpf(f32) is not defined. MinGW has
1407 // it, but it's just a wrapper around ldexp.
1408 if (TT.isOSWindows()) {
1410 if (isOperationExpand(Op, MVT::f32))
1411 setOperationAction(Op, MVT::f32, Promote);
1412 }
1413
1414 // LegalizeDAG currently can't expand fp16 LDEXP/FREXP on targets where i16
1415 // isn't legal.
1417 if (isOperationExpand(Op, MVT::f16))
1418 setOperationAction(Op, MVT::f16, Promote);
1419
1420 // We have target-specific dag combine patterns for the following nodes:
1421 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1424
1425 if (Subtarget->hasMVEIntegerOps())
1427
1428 if (Subtarget->hasV6Ops())
1430 if (Subtarget->isThumb1Only())
1432 // Attempt to lower smin/smax to ssat/usat
1433 if ((!Subtarget->isThumb() && Subtarget->hasV6Ops()) ||
1434 Subtarget->isThumb2()) {
1436 }
1437
1439
1440 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1441 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1443 else
1445
1446 //// temporary - rewrite interface to use type
1449 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1451 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1453
1454 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1455 // are at least 4 bytes aligned.
1457
1458 // Prefer likely predicted branches to selects on out-of-order cores.
1459 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1460
1462 Align::fromLog2(Subtarget->getPreferBranchLogAlignment()));
1464 Align::fromLog2(Subtarget->getPreferBranchLogAlignment()));
1465
1466 setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4));
1467
1468 IsStrictFPEnabled = true;
1469}
1470
1472 return Subtarget->useSoftFloat();
1473}
1474
1476 return !Subtarget->isThumb1Only() && VT.getSizeInBits() <= 32;
1477}
1478
1479// FIXME: It might make sense to define the representative register class as the
1480// nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1481// a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1482// SPR's representative would be DPR_VFP2. This should work well if register
1483// pressure tracking were modified such that a register use would increment the
1484// pressure of the register class's representative and all of it's super
1485// classes' representatives transitively. We have not implemented this because
1486// of the difficulty prior to coalescing of modeling operand register classes
1487// due to the common occurrence of cross class copies and subregister insertions
1488// and extractions.
1489std::pair<const TargetRegisterClass *, uint8_t>
1491 MVT VT) const {
1492 const TargetRegisterClass *RRC = nullptr;
1493 uint8_t Cost = 1;
1494 switch (VT.SimpleTy) {
1495 default:
1497 // Use DPR as representative register class for all floating point
1498 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1499 // the cost is 1 for both f32 and f64.
1500 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1501 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1502 RRC = &ARM::DPRRegClass;
1503 // When NEON is used for SP, only half of the register file is available
1504 // because operations that define both SP and DP results will be constrained
1505 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1506 // coalescing by double-counting the SP regs. See the FIXME above.
1507 if (Subtarget->useNEONForSinglePrecisionFP())
1508 Cost = 2;
1509 break;
1510 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1511 case MVT::v4f32: case MVT::v2f64:
1512 RRC = &ARM::DPRRegClass;
1513 Cost = 2;
1514 break;
1515 case MVT::v4i64:
1516 RRC = &ARM::DPRRegClass;
1517 Cost = 4;
1518 break;
1519 case MVT::v8i64:
1520 RRC = &ARM::DPRRegClass;
1521 Cost = 8;
1522 break;
1523 }
1524 return std::make_pair(RRC, Cost);
1525}
1526
1528 EVT VT) const {
1529 if (!VT.isVector())
1530 return getPointerTy(DL);
1531
1532 // MVE has a predicate register.
1533 if (Subtarget->hasMVEIntegerOps())
1534 return EVT::getVectorVT(C, MVT::i1, VT.getVectorElementCount());
1535
1537}
1538
1539/// getRegClassFor - Return the register class that should be used for the
1540/// specified value type.
1541const TargetRegisterClass *
1542ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1543 (void)isDivergent;
1544 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1545 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1546 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1547 // MVE Q registers.
1548 if (Subtarget->hasNEON()) {
1549 if (VT == MVT::v4i64)
1550 return &ARM::QQPRRegClass;
1551 if (VT == MVT::v8i64)
1552 return &ARM::QQQQPRRegClass;
1553 }
1554 if (Subtarget->hasMVEIntegerOps()) {
1555 if (VT == MVT::v4i64)
1556 return &ARM::MQQPRRegClass;
1557 if (VT == MVT::v8i64)
1558 return &ARM::MQQQQPRRegClass;
1559 }
1561}
1562
1563// memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1564// source/dest is aligned and the copy size is large enough. We therefore want
1565// to align such objects passed to memory intrinsics.
1567 Align &PrefAlign) const {
1568 if (!isa<MemIntrinsic>(CI))
1569 return false;
1570 MinSize = 8;
1571 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1572 // cycle faster than 4-byte aligned LDM.
1573 PrefAlign =
1574 (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? Align(8) : Align(4));
1575 return true;
1576}
1577
1578// Create a fast isel object.
1580 FunctionLoweringInfo &funcInfo, const TargetLibraryInfo *libInfo,
1581 const LibcallLoweringInfo *libcallLowering) const {
1582 return ARM::createFastISel(funcInfo, libInfo, libcallLowering);
1583}
1584
1586 unsigned NumVals = N->getNumValues();
1587 if (!NumVals)
1588 return Sched::RegPressure;
1589
1590 for (unsigned i = 0; i != NumVals; ++i) {
1591 EVT VT = N->getValueType(i);
1592 if (VT == MVT::Glue || VT == MVT::Other)
1593 continue;
1594 if (VT.isFloatingPoint() || VT.isVector())
1595 return Sched::ILP;
1596 }
1597
1598 if (!N->isMachineOpcode())
1599 return Sched::RegPressure;
1600
1601 // Load are scheduled for latency even if there instruction itinerary
1602 // is not available.
1603 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1604 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1605
1606 if (MCID.getNumDefs() == 0)
1607 return Sched::RegPressure;
1608 if (!Itins->isEmpty() &&
1609 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2U)
1610 return Sched::ILP;
1611
1612 return Sched::RegPressure;
1613}
1614
1615//===----------------------------------------------------------------------===//
1616// Lowering Code
1617//===----------------------------------------------------------------------===//
1618
1619static bool isSRL16(const SDValue &Op) {
1620 if (Op.getOpcode() != ISD::SRL)
1621 return false;
1622 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1623 return Const->getZExtValue() == 16;
1624 return false;
1625}
1626
1627static bool isSRA16(const SDValue &Op) {
1628 if (Op.getOpcode() != ISD::SRA)
1629 return false;
1630 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1631 return Const->getZExtValue() == 16;
1632 return false;
1633}
1634
1635static bool isSHL16(const SDValue &Op) {
1636 if (Op.getOpcode() != ISD::SHL)
1637 return false;
1638 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1639 return Const->getZExtValue() == 16;
1640 return false;
1641}
1642
1643// Check for a signed 16-bit value. We special case SRA because it makes it
1644// more simple when also looking for SRAs that aren't sign extending a
1645// smaller value. Without the check, we'd need to take extra care with
1646// checking order for some operations.
1647static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1648 if (isSRA16(Op))
1649 return isSHL16(Op.getOperand(0));
1650 return DAG.ComputeNumSignBits(Op) == 17;
1651}
1652
1653/// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1655 switch (CC) {
1656 default: llvm_unreachable("Unknown condition code!");
1657 case ISD::SETNE: return ARMCC::NE;
1658 case ISD::SETEQ: return ARMCC::EQ;
1659 case ISD::SETGT: return ARMCC::GT;
1660 case ISD::SETGE: return ARMCC::GE;
1661 case ISD::SETLT: return ARMCC::LT;
1662 case ISD::SETLE: return ARMCC::LE;
1663 case ISD::SETUGT: return ARMCC::HI;
1664 case ISD::SETUGE: return ARMCC::HS;
1665 case ISD::SETULT: return ARMCC::LO;
1666 case ISD::SETULE: return ARMCC::LS;
1667 }
1668}
1669
1670/// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1672 ARMCC::CondCodes &CondCode2) {
1673 CondCode2 = ARMCC::AL;
1674 switch (CC) {
1675 default: llvm_unreachable("Unknown FP condition!");
1676 case ISD::SETEQ:
1677 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1678 case ISD::SETGT:
1679 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1680 case ISD::SETGE:
1681 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1682 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1683 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1684 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1685 case ISD::SETO: CondCode = ARMCC::VC; break;
1686 case ISD::SETUO: CondCode = ARMCC::VS; break;
1687 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1688 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1689 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1690 case ISD::SETLT:
1691 case ISD::SETULT: CondCode = ARMCC::LT; break;
1692 case ISD::SETLE:
1693 case ISD::SETULE: CondCode = ARMCC::LE; break;
1694 case ISD::SETNE:
1695 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1696 }
1697}
1698
1699//===----------------------------------------------------------------------===//
1700// Calling Convention Implementation
1701//===----------------------------------------------------------------------===//
1702
1703/// getEffectiveCallingConv - Get the effective calling convention, taking into
1704/// account presence of floating point hardware and calling convention
1705/// limitations, such as support for variadic functions.
1708 bool isVarArg) const {
1709 switch (CC) {
1710 default:
1711 // Unknown CCs are rejected when calling convention lowering is required.
1714 case CallingConv::GHC:
1716 return CC;
1722 case CallingConv::Swift:
1725 case CallingConv::C:
1726 case CallingConv::Tail:
1727 if (!Subtarget->isAAPCS_ABI())
1728 return CallingConv::ARM_APCS;
1729 else if (Subtarget->isTargetHardFloat() && !isVarArg)
1731 else
1733 case CallingConv::Fast:
1735 if (!Subtarget->isAAPCS_ABI()) {
1736 if (Subtarget->hasFPRegs() && !Subtarget->isThumb1Only() && !isVarArg)
1737 return CallingConv::Fast;
1738 return CallingConv::ARM_APCS;
1739 } else if (Subtarget->hasFPRegs() && !Subtarget->isThumb1Only() &&
1740 !Subtarget->useSoftFloat() && !isVarArg)
1742 else
1744 }
1745}
1746
1748 bool isVarArg) const {
1749 return CCAssignFnForNode(CC, false, isVarArg);
1750}
1751
1753 bool isVarArg) const {
1754 return CCAssignFnForNode(CC, true, isVarArg);
1755}
1756
1757/// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1758/// CallingConvention.
1759CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1760 bool Return,
1761 bool isVarArg) const {
1762 switch (getEffectiveCallingConv(CC, isVarArg)) {
1763 default:
1764 report_fatal_error("Unsupported calling convention");
1766 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1768 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1770 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1771 case CallingConv::Fast:
1772 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1773 case CallingConv::GHC:
1774 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1776 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1778 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1780 return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check);
1781 }
1782}
1783
1784SDValue ARMTargetLowering::MoveToHPR(const SDLoc &dl, SelectionDAG &DAG,
1785 MVT LocVT, MVT ValVT, SDValue Val) const {
1786 Val = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocVT.getSizeInBits()),
1787 Val);
1788 if (Subtarget->hasFullFP16()) {
1789 Val = DAG.getNode(ARMISD::VMOVhr, dl, ValVT, Val);
1790 } else {
1791 Val = DAG.getNode(ISD::TRUNCATE, dl,
1792 MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
1793 Val = DAG.getNode(ISD::BITCAST, dl, ValVT, Val);
1794 }
1795 return Val;
1796}
1797
1798SDValue ARMTargetLowering::MoveFromHPR(const SDLoc &dl, SelectionDAG &DAG,
1799 MVT LocVT, MVT ValVT,
1800 SDValue Val) const {
1801 if (Subtarget->hasFullFP16()) {
1802 Val = DAG.getNode(ARMISD::VMOVrh, dl,
1803 MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
1804 } else {
1805 Val = DAG.getNode(ISD::BITCAST, dl,
1806 MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
1807 Val = DAG.getNode(ISD::ZERO_EXTEND, dl,
1808 MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
1809 }
1810 return DAG.getNode(ISD::BITCAST, dl, LocVT, Val);
1811}
1812
1813/// LowerCallResult - Lower the result values of a call into the
1814/// appropriate copies out of appropriate physical registers.
1815SDValue ARMTargetLowering::LowerCallResult(
1816 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool isVarArg,
1817 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1818 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1819 SDValue ThisVal, bool isCmseNSCall) const {
1820 // Assign locations to each value returned by this call.
1822 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1823 *DAG.getContext());
1824 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1825
1826 // Copy all of the result registers out of their specified physreg.
1827 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1828 CCValAssign VA = RVLocs[i];
1829
1830 // Pass 'this' value directly from the argument to return value, to avoid
1831 // reg unit interference
1832 if (i == 0 && isThisReturn) {
1833 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1834 "unexpected return calling convention register assignment");
1835 InVals.push_back(ThisVal);
1836 continue;
1837 }
1838
1839 SDValue Val;
1840 if (VA.needsCustom() &&
1841 (VA.getLocVT() == MVT::f64 || VA.getLocVT() == MVT::v2f64)) {
1842 // Handle f64 or half of a v2f64.
1843 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1844 InGlue);
1845 Chain = Lo.getValue(1);
1846 InGlue = Lo.getValue(2);
1847 VA = RVLocs[++i]; // skip ahead to next loc
1848 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1849 InGlue);
1850 Chain = Hi.getValue(1);
1851 InGlue = Hi.getValue(2);
1852 if (!Subtarget->isLittle())
1853 std::swap (Lo, Hi);
1854 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1855
1856 if (VA.getLocVT() == MVT::v2f64) {
1857 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1858 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1859 DAG.getConstant(0, dl, MVT::i32));
1860
1861 VA = RVLocs[++i]; // skip ahead to next loc
1862 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InGlue);
1863 Chain = Lo.getValue(1);
1864 InGlue = Lo.getValue(2);
1865 VA = RVLocs[++i]; // skip ahead to next loc
1866 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InGlue);
1867 Chain = Hi.getValue(1);
1868 InGlue = Hi.getValue(2);
1869 if (!Subtarget->isLittle())
1870 std::swap (Lo, Hi);
1871 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1872 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1873 DAG.getConstant(1, dl, MVT::i32));
1874 }
1875 } else {
1876 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1877 InGlue);
1878 Chain = Val.getValue(1);
1879 InGlue = Val.getValue(2);
1880 }
1881
1882 switch (VA.getLocInfo()) {
1883 default: llvm_unreachable("Unknown loc info!");
1884 case CCValAssign::Full: break;
1885 case CCValAssign::BCvt:
1886 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1887 break;
1888 }
1889
1890 // f16 arguments have their size extended to 4 bytes and passed as if they
1891 // had been copied to the LSBs of a 32-bit register.
1892 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
1893 if (VA.needsCustom() &&
1894 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
1895 Val = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Val);
1896
1897 // On CMSE Non-secure Calls, call results (returned values) whose bitwidth
1898 // is less than 32 bits must be sign- or zero-extended after the call for
1899 // security reasons. Although the ABI mandates an extension done by the
1900 // callee, the latter cannot be trusted to follow the rules of the ABI.
1901 const ISD::InputArg &Arg = Ins[VA.getValNo()];
1902 if (isCmseNSCall && Arg.ArgVT.isScalarInteger() &&
1903 VA.getLocVT().isScalarInteger() && Arg.ArgVT.bitsLT(MVT::i32))
1904 Val = handleCMSEValue(Val, Arg, DAG, dl);
1905
1906 InVals.push_back(Val);
1907 }
1908
1909 return Chain;
1910}
1911
1912std::pair<SDValue, MachinePointerInfo> ARMTargetLowering::computeAddrForCallArg(
1913 const SDLoc &dl, SelectionDAG &DAG, const CCValAssign &VA, SDValue StackPtr,
1914 bool IsTailCall, int SPDiff) const {
1915 SDValue DstAddr;
1916 MachinePointerInfo DstInfo;
1917 int32_t Offset = VA.getLocMemOffset();
1919
1920 if (IsTailCall) {
1921 Offset += SPDiff;
1922 auto PtrVT = getPointerTy(DAG.getDataLayout());
1923 int Size = VA.getLocVT().getFixedSizeInBits() / 8;
1924 int FI = MF.getFrameInfo().CreateFixedObject(Size, Offset, true);
1925 DstAddr = DAG.getFrameIndex(FI, PtrVT);
1926 DstInfo =
1928 } else {
1929 SDValue PtrOff = DAG.getIntPtrConstant(Offset, dl);
1930 DstAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1931 StackPtr, PtrOff);
1932 DstInfo =
1934 }
1935
1936 return std::make_pair(DstAddr, DstInfo);
1937}
1938
1939// Returns the type of copying which is required to set up a byval argument to
1940// a tail-called function. This isn't needed for non-tail calls, because they
1941// always need the equivalent of CopyOnce, but tail-calls sometimes need two to
1942// avoid clobbering another argument (CopyViaTemp), and sometimes can be
1943// optimised to zero copies when forwarding an argument from the caller's
1944// caller (NoCopy).
1945ARMTargetLowering::ByValCopyKind ARMTargetLowering::ByValNeedsCopyForTailCall(
1946 SelectionDAG &DAG, SDValue Src, SDValue Dst, ISD::ArgFlagsTy Flags) const {
1947 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1948 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
1949
1950 // Globals are always safe to copy from.
1952 return CopyOnce;
1953
1954 // Can only analyse frame index nodes, conservatively assume we need a
1955 // temporary.
1956 auto *SrcFrameIdxNode = dyn_cast<FrameIndexSDNode>(Src);
1957 auto *DstFrameIdxNode = dyn_cast<FrameIndexSDNode>(Dst);
1958 if (!SrcFrameIdxNode || !DstFrameIdxNode)
1959 return CopyViaTemp;
1960
1961 int SrcFI = SrcFrameIdxNode->getIndex();
1962 int DstFI = DstFrameIdxNode->getIndex();
1963 assert(MFI.isFixedObjectIndex(DstFI) &&
1964 "byval passed in non-fixed stack slot");
1965
1966 int64_t SrcOffset = MFI.getObjectOffset(SrcFI);
1967 int64_t DstOffset = MFI.getObjectOffset(DstFI);
1968
1969 // If the source is in the local frame, then the copy to the argument memory
1970 // is always valid.
1971 bool FixedSrc = MFI.isFixedObjectIndex(SrcFI);
1972 if (!FixedSrc ||
1973 (FixedSrc && SrcOffset < -(int64_t)AFI->getArgRegsSaveSize()))
1974 return CopyOnce;
1975
1976 // In the case of byval arguments split between registers and the stack,
1977 // computeAddrForCallArg returns a FrameIndex which corresponds only to the
1978 // stack portion, but the Src SDValue will refer to the full value, including
1979 // the local stack memory that the register portion gets stored into. We only
1980 // need to compare them for equality, so normalise on the full value version.
1981 uint64_t RegSize = Flags.getByValSize() - MFI.getObjectSize(DstFI);
1982 DstOffset -= RegSize;
1983
1984 // If the value is already in the correct location, then no copying is
1985 // needed. If not, then we need to copy via a temporary.
1986 if (SrcOffset == DstOffset)
1987 return NoCopy;
1988 else
1989 return CopyViaTemp;
1990}
1991
1992void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1993 SDValue Chain, SDValue &Arg,
1994 RegsToPassVector &RegsToPass,
1995 CCValAssign &VA, CCValAssign &NextVA,
1996 SDValue &StackPtr,
1997 SmallVectorImpl<SDValue> &MemOpChains,
1998 bool IsTailCall,
1999 int SPDiff) const {
2000 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2001 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2002 unsigned id = Subtarget->isLittle() ? 0 : 1;
2003 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
2004
2005 if (NextVA.isRegLoc())
2006 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
2007 else {
2008 assert(NextVA.isMemLoc());
2009 if (!StackPtr.getNode())
2010 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
2012
2013 SDValue DstAddr;
2014 MachinePointerInfo DstInfo;
2015 std::tie(DstAddr, DstInfo) =
2016 computeAddrForCallArg(dl, DAG, NextVA, StackPtr, IsTailCall, SPDiff);
2017 MemOpChains.push_back(
2018 DAG.getStore(Chain, dl, fmrrd.getValue(1 - id), DstAddr, DstInfo));
2019 }
2020}
2021
2022static bool canGuaranteeTCO(CallingConv::ID CC, bool GuaranteeTailCalls) {
2023 return (CC == CallingConv::Fast && GuaranteeTailCalls) ||
2025}
2026
2027/// LowerCall - Lowering a call into a callseq_start <-
2028/// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2029/// nodes.
2030SDValue
2031ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2032 SmallVectorImpl<SDValue> &InVals) const {
2033 SelectionDAG &DAG = CLI.DAG;
2034 SDLoc &dl = CLI.DL;
2035 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2036 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2037 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2038 SDValue Chain = CLI.Chain;
2039 SDValue Callee = CLI.Callee;
2040 bool &isTailCall = CLI.IsTailCall;
2041 CallingConv::ID CallConv = CLI.CallConv;
2042 bool doesNotRet = CLI.DoesNotReturn;
2043 bool isVarArg = CLI.IsVarArg;
2044 const CallBase *CB = CLI.CB;
2045
2047 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2048 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2049 MachineFunction::CallSiteInfo CSInfo;
2050 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2051 bool isThisReturn = false;
2052 bool isCmseNSCall = false;
2053 bool isSibCall = false;
2054 bool PreferIndirect = false;
2055 bool GuardWithBTI = false;
2056
2057 // Analyze operands of the call, assigning locations to each operand.
2059 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2060 *DAG.getContext());
2061 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2062
2063 // Lower 'returns_twice' calls to a pseudo-instruction.
2064 if (CLI.CB && CLI.CB->getAttributes().hasFnAttr(Attribute::ReturnsTwice) &&
2065 !Subtarget->noBTIAtReturnTwice())
2066 GuardWithBTI = AFI->branchTargetEnforcement();
2067
2068 // Set type id for call site info.
2069 setTypeIdForCallsiteInfo(CB, MF, CSInfo);
2070
2071 // Determine whether this is a non-secure function call.
2072 if (CLI.CB && CLI.CB->getAttributes().hasFnAttr("cmse_nonsecure_call"))
2073 isCmseNSCall = true;
2074
2075 // Disable tail calls if they're not supported.
2076 if (!Subtarget->supportsTailCall())
2077 isTailCall = false;
2078
2079 // For both the non-secure calls and the returns from a CMSE entry function,
2080 // the function needs to do some extra work after the call, or before the
2081 // return, respectively, thus it cannot end with a tail call
2082 if (isCmseNSCall || AFI->isCmseNSEntryFunction())
2083 isTailCall = false;
2084
2085 if (isa<GlobalAddressSDNode>(Callee)) {
2086 // If we're optimizing for minimum size and the function is called three or
2087 // more times in this block, we can improve codesize by calling indirectly
2088 // as BLXr has a 16-bit encoding.
2089 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2090 if (CLI.CB) {
2091 auto *BB = CLI.CB->getParent();
2092 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2093 count_if(GV->users(), [&BB](const User *U) {
2094 return isa<Instruction>(U) &&
2095 cast<Instruction>(U)->getParent() == BB;
2096 }) > 2;
2097 }
2098 }
2099 if (isTailCall) {
2100 // Check if it's really possible to do a tail call.
2101 isTailCall =
2102 IsEligibleForTailCallOptimization(CLI, CCInfo, ArgLocs, PreferIndirect);
2103
2104 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt &&
2105 CallConv != CallingConv::Tail && CallConv != CallingConv::SwiftTail)
2106 isSibCall = true;
2107
2108 // We don't support GuaranteedTailCallOpt for ARM, only automatically
2109 // detected sibcalls.
2110 if (isTailCall)
2111 ++NumTailCalls;
2112 }
2113
2114 if (!isTailCall && CLI.CB && CLI.CB->isMustTailCall())
2115 report_fatal_error("failed to perform tail call elimination on a call "
2116 "site marked musttail");
2117
2118 // Get a count of how many bytes are to be pushed on the stack.
2119 unsigned NumBytes = CCInfo.getStackSize();
2120
2121 // SPDiff is the byte offset of the call's argument area from the callee's.
2122 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2123 // by this amount for a tail call. In a sibling call it must be 0 because the
2124 // caller will deallocate the entire stack and the callee still expects its
2125 // arguments to begin at SP+0. Completely unused for non-tail calls.
2126 int SPDiff = 0;
2127
2128 if (isTailCall && !isSibCall) {
2129 auto FuncInfo = MF.getInfo<ARMFunctionInfo>();
2130 unsigned NumReusableBytes = FuncInfo->getArgumentStackSize();
2131
2132 // Since callee will pop argument stack as a tail call, we must keep the
2133 // popped size 16-byte aligned.
2134 MaybeAlign StackAlign = DAG.getDataLayout().getStackAlignment();
2135 assert(StackAlign && "data layout string is missing stack alignment");
2136 NumBytes = alignTo(NumBytes, *StackAlign);
2137
2138 // SPDiff will be negative if this tail call requires more space than we
2139 // would automatically have in our incoming argument space. Positive if we
2140 // can actually shrink the stack.
2141 SPDiff = NumReusableBytes - NumBytes;
2142
2143 // If this call requires more stack than we have available from
2144 // LowerFormalArguments, tell FrameLowering to reserve space for it.
2145 if (SPDiff < 0 && AFI->getArgRegsSaveSize() < (unsigned)-SPDiff)
2146 AFI->setArgRegsSaveSize(-SPDiff);
2147 }
2148
2149 if (isSibCall) {
2150 // For sibling tail calls, memory operands are available in our caller's stack.
2151 NumBytes = 0;
2152 } else {
2153 // Adjust the stack pointer for the new arguments...
2154 // These operations are automatically eliminated by the prolog/epilog pass
2155 Chain = DAG.getCALLSEQ_START(Chain, isTailCall ? 0 : NumBytes, 0, dl);
2156 }
2157
2159 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2160
2161 RegsToPassVector RegsToPass;
2162 SmallVector<SDValue, 8> MemOpChains;
2163
2164 // A musttail call in a variadic function must receive the caller's unnamed
2165 // register arguments unchanged. The forwarded set is disjoint from the named
2166 // arguments handled below.
2167 if (isVarArg && CLI.CB && CLI.CB->isMustTailCall()) {
2168 const auto &Forwards = AFI->getForwardedMustTailRegParms();
2169 for (const ForwardedRegister &F : Forwards) {
2170 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2171 RegsToPass.push_back(std::make_pair(F.PReg, Val));
2172 }
2173 }
2174
2175 // If we are doing a tail-call, any byval arguments will be written to stack
2176 // space which was used for incoming arguments. If any the values being used
2177 // are incoming byval arguments to this function, then they might be
2178 // overwritten by the stores of the outgoing arguments. To avoid this, we
2179 // need to make a temporary copy of them in local stack space, then copy back
2180 // to the argument area.
2181 DenseMap<unsigned, SDValue> ByValTemporaries;
2182 SDValue ByValTempChain;
2183 if (isTailCall) {
2184 SmallVector<SDValue, 8> ByValCopyChains;
2185 for (const CCValAssign &VA : ArgLocs) {
2186 unsigned ArgIdx = VA.getValNo();
2187 SDValue Src = OutVals[ArgIdx];
2188 ISD::ArgFlagsTy Flags = Outs[ArgIdx].Flags;
2189
2190 if (!Flags.isByVal())
2191 continue;
2192
2193 SDValue Dst;
2194 MachinePointerInfo DstInfo;
2195 std::tie(Dst, DstInfo) =
2196 computeAddrForCallArg(dl, DAG, VA, SDValue(), true, SPDiff);
2197 ByValCopyKind Copy = ByValNeedsCopyForTailCall(DAG, Src, Dst, Flags);
2198
2199 if (Copy == NoCopy) {
2200 // If the argument is already at the correct offset on the stack
2201 // (because we are forwarding a byval argument from our caller), we
2202 // don't need any copying.
2203 continue;
2204 } else if (Copy == CopyOnce) {
2205 // If the argument is in our local stack frame, no other argument
2206 // preparation can clobber it, so we can copy it to the final location
2207 // later.
2208 ByValTemporaries[ArgIdx] = Src;
2209 } else {
2210 assert(Copy == CopyViaTemp && "unexpected enum value");
2211 // If we might be copying this argument from the outgoing argument
2212 // stack area, we need to copy via a temporary in the local stack
2213 // frame.
2214 int TempFrameIdx = MFI.CreateStackObject(
2215 Flags.getByValSize(), Flags.getNonZeroByValAlign(), false);
2216 SDValue Temp =
2217 DAG.getFrameIndex(TempFrameIdx, getPointerTy(DAG.getDataLayout()));
2218
2219 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2220 SDValue AlignNode =
2221 DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32);
2222
2223 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2224 SDValue Ops[] = {Chain, Temp, Src, SizeNode, AlignNode};
2225 ByValCopyChains.push_back(
2226 DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, Ops));
2227 ByValTemporaries[ArgIdx] = Temp;
2228 }
2229 }
2230 if (!ByValCopyChains.empty())
2231 ByValTempChain =
2232 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, ByValCopyChains);
2233 }
2234
2235 // During a tail call, stores to the argument area must happen after all of
2236 // the function's incoming arguments have been loaded because they may alias.
2237 // This is done by folding in a TokenFactor from LowerFormalArguments, but
2238 // there's no point in doing so repeatedly so this tracks whether that's
2239 // happened yet.
2240 bool AfterFormalArgLoads = false;
2241
2242 // Walk the register/memloc assignments, inserting copies/loads. In the case
2243 // of tail call optimization, arguments are handled later.
2244 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2245 i != e;
2246 ++i, ++realArgIdx) {
2247 CCValAssign &VA = ArgLocs[i];
2248 SDValue Arg = OutVals[realArgIdx];
2249 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2250 bool isByVal = Flags.isByVal();
2251
2252 // Promote the value if needed.
2253 switch (VA.getLocInfo()) {
2254 default: llvm_unreachable("Unknown loc info!");
2255 case CCValAssign::Full: break;
2256 case CCValAssign::SExt:
2257 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2258 break;
2259 case CCValAssign::ZExt:
2260 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2261 break;
2262 case CCValAssign::AExt:
2263 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2264 break;
2265 case CCValAssign::BCvt:
2266 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2267 break;
2268 }
2269
2270 if (isTailCall && VA.isMemLoc() && !AfterFormalArgLoads) {
2271 Chain = DAG.getStackArgumentTokenFactor(Chain);
2272 if (ByValTempChain) {
2273 // In case of large byval copies, re-using the stackframe for tail-calls
2274 // can lead to overwriting incoming arguments on the stack. Force
2275 // loading these stack arguments before the copy to avoid that.
2276 SmallVector<SDValue, 8> IncomingLoad;
2277 for (unsigned I = 0; I < OutVals.size(); ++I) {
2278 if (Outs[I].Flags.isByVal())
2279 continue;
2280
2281 SDValue OutVal = OutVals[I];
2282 LoadSDNode *OutLN = dyn_cast_or_null<LoadSDNode>(OutVal);
2283 if (!OutLN)
2284 continue;
2285
2286 FrameIndexSDNode *FIN =
2288 if (!FIN)
2289 continue;
2290
2291 if (!MFI.isFixedObjectIndex(FIN->getIndex()))
2292 continue;
2293
2294 for (const CCValAssign &VA : ArgLocs) {
2295 if (VA.isMemLoc())
2296 IncomingLoad.push_back(OutVal.getValue(1));
2297 }
2298 }
2299
2300 // Update the chain to force loads for potentially clobbered argument
2301 // loads to happen before the byval copy.
2302 if (!IncomingLoad.empty()) {
2303 IncomingLoad.push_back(Chain);
2304 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, IncomingLoad);
2305 }
2306
2307 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chain,
2308 ByValTempChain);
2309 }
2310 AfterFormalArgLoads = true;
2311 }
2312
2313 // f16 arguments have their size extended to 4 bytes and passed as if they
2314 // had been copied to the LSBs of a 32-bit register.
2315 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
2316 if (VA.needsCustom() &&
2317 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) {
2318 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
2319 } else {
2320 // f16 arguments could have been extended prior to argument lowering.
2321 // Mask them arguments if this is a CMSE nonsecure call.
2322 auto ArgVT = Outs[realArgIdx].ArgVT;
2323 if (isCmseNSCall && (ArgVT == MVT::f16)) {
2324 auto LocBits = VA.getLocVT().getSizeInBits();
2325 auto MaskValue = APInt::getLowBitsSet(LocBits, ArgVT.getSizeInBits());
2326 SDValue Mask =
2327 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
2328 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
2329 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
2330 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2331 }
2332 }
2333
2334 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2335 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
2336 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2337 DAG.getConstant(0, dl, MVT::i32));
2338 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2339 DAG.getConstant(1, dl, MVT::i32));
2340
2341 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, VA, ArgLocs[++i],
2342 StackPtr, MemOpChains, isTailCall, SPDiff);
2343
2344 VA = ArgLocs[++i]; // skip ahead to next loc
2345 if (VA.isRegLoc()) {
2346 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, VA, ArgLocs[++i],
2347 StackPtr, MemOpChains, isTailCall, SPDiff);
2348 } else {
2349 assert(VA.isMemLoc());
2350 SDValue DstAddr;
2351 MachinePointerInfo DstInfo;
2352 std::tie(DstAddr, DstInfo) =
2353 computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2354 MemOpChains.push_back(DAG.getStore(Chain, dl, Op1, DstAddr, DstInfo));
2355 }
2356 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
2357 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2358 StackPtr, MemOpChains, isTailCall, SPDiff);
2359 } else if (VA.isRegLoc()) {
2360 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2361 Outs[0].VT == MVT::i32) {
2362 assert(VA.getLocVT() == MVT::i32 &&
2363 "unexpected calling convention register assignment");
2364 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2365 "unexpected use of 'returned'");
2366 isThisReturn = true;
2367 }
2368 const TargetOptions &Options = DAG.getTarget().Options;
2369 if (Options.EmitCallSiteInfo)
2370 CSInfo.ArgRegPairs.emplace_back(VA.getLocReg(), i);
2371 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2372 } else if (isByVal) {
2373 assert(VA.isMemLoc());
2374 unsigned offset = 0;
2375
2376 // True if this byval aggregate will be split between registers
2377 // and memory.
2378 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2379 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2380
2381 SDValue ByValSrc;
2382 bool NeedsStackCopy;
2383 if (auto It = ByValTemporaries.find(realArgIdx);
2384 It != ByValTemporaries.end()) {
2385 ByValSrc = It->second;
2386 NeedsStackCopy = true;
2387 } else {
2388 ByValSrc = Arg;
2389 NeedsStackCopy = !isTailCall;
2390 }
2391
2392 // If part of the argument is in registers, load them.
2393 if (CurByValIdx < ByValArgsCount) {
2394 unsigned RegBegin, RegEnd;
2395 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2396
2397 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2398 unsigned int i, j;
2399 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2400 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2401 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, ByValSrc, Const);
2402 SDValue Load =
2403 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(),
2404 DAG.InferPtrAlign(AddArg));
2405 MemOpChains.push_back(Load.getValue(1));
2406 RegsToPass.push_back(std::make_pair(j, Load));
2407 }
2408
2409 // If parameter size outsides register area, "offset" value
2410 // helps us to calculate stack slot for remained part properly.
2411 offset = RegEnd - RegBegin;
2412
2413 CCInfo.nextInRegsParam();
2414 }
2415
2416 // If the memory part of the argument isn't already in the correct place
2417 // (which can happen with tail calls), copy it into the argument area.
2418 if (NeedsStackCopy && Flags.getByValSize() > 4 * offset) {
2419 auto PtrVT = getPointerTy(DAG.getDataLayout());
2420 SDValue Dst;
2421 MachinePointerInfo DstInfo;
2422 std::tie(Dst, DstInfo) =
2423 computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2424 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2425 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, ByValSrc, SrcOffset);
2426 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2427 MVT::i32);
2428 SDValue AlignNode =
2429 DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32);
2430
2431 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2432 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2433 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2434 Ops));
2435 }
2436 } else {
2437 assert(VA.isMemLoc());
2438 SDValue DstAddr;
2439 MachinePointerInfo DstInfo;
2440 std::tie(DstAddr, DstInfo) =
2441 computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2442
2443 SDValue Store = DAG.getStore(Chain, dl, Arg, DstAddr, DstInfo);
2444 MemOpChains.push_back(Store);
2445 }
2446 }
2447
2448 if (!MemOpChains.empty())
2449 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2450
2451 // Build a sequence of copy-to-reg nodes chained together with token chain
2452 // and flag operands which copy the outgoing args into the appropriate regs.
2453 SDValue InGlue;
2454 for (const auto &[Reg, N] : RegsToPass) {
2455 Chain = DAG.getCopyToReg(Chain, dl, Reg, N, InGlue);
2456 InGlue = Chain.getValue(1);
2457 }
2458
2459 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2460 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2461 // node so that legalize doesn't hack it.
2462 bool isDirect = false;
2463
2464 const TargetMachine &TM = getTargetMachine();
2465 const Triple &TT = TM.getTargetTriple();
2466 const GlobalValue *GVal = nullptr;
2467 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2468 GVal = G->getGlobal();
2469 bool isStub = !TM.shouldAssumeDSOLocal(GVal) && TT.isOSBinFormatMachO();
2470
2471 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2472 bool isLocalARMFunc = false;
2473 auto PtrVt = getPointerTy(DAG.getDataLayout());
2474
2475 if (Subtarget->genLongCalls()) {
2476 bool isPIC = isPositionIndependent() && !TT.isOSWindows();
2477 if (isPIC && Subtarget->genExecuteOnly())
2478 reportFatalUsageError("long-calls with execute-only and "
2479 "position-independent code is not supported");
2480 if (Subtarget->isROPI())
2481 reportFatalUsageError("long-calls with ROPI is not currently supported");
2482
2483 // Handle a global address or an external symbol. If it's not one of
2484 // those, the target's already in a register, so we don't need to do
2485 // anything extra.
2486 if (isa<GlobalAddressSDNode>(Callee)) {
2487 if (Subtarget->genExecuteOnly()) {
2488 // Execute-only forbids constant pools in .text, so use movw/movt.
2489 // fPIC is not supported with execute-only.
2490 if (Subtarget->useMovt())
2491 ++NumMovwMovt;
2492 Callee = DAG.getNode(ARMISD::Wrapper, dl, PtrVt,
2493 DAG.getTargetGlobalAddress(GVal, dl, PtrVt));
2494 } else if (isPIC) {
2495 // PIC without execute-only: use GOT-based addressing.
2496 // DSO-local symbols use a plain PC-relative WrapperPIC;
2497 // non-DSO-local symbols additionally load the address from the GOT.
2499 GVal, dl, PtrVt, 0, GVal->isDSOLocal() ? 0 : ARMII::MO_GOT);
2500 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVt, G);
2501 if (!GVal->isDSOLocal())
2502 Callee =
2503 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
2505 } else {
2506 // Neither execute-only nor PIC: load the address from a constant pool.
2507 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2508 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2509 GVal, ARMPCLabelIndex, ARMCP::CPValue, 0);
2510
2511 // Get the address of the callee into a register
2512 SDValue Addr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2513 Addr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Addr);
2514 Callee = DAG.getLoad(
2515 PtrVt, dl, DAG.getEntryNode(), Addr,
2517 }
2518 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2519 const char *Sym = S->getSymbol();
2520
2521 if (Subtarget->genExecuteOnly()) {
2522 // Execute-only forbids constant pools in .text, so use movw/movt.
2523 // fPIC is not supported with execute-only.
2524 if (Subtarget->useMovt())
2525 ++NumMovwMovt;
2526 Callee = DAG.getNode(ARMISD::Wrapper, dl, PtrVt,
2527 DAG.getTargetExternalSymbol(Sym, PtrVt, 0));
2528 } else if (isPIC) {
2529 // PIC without execute-only: load the symbol's address from the GOT via
2530 // a GOT_PREL constant pool entry consumed by a PICLDR.
2531 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2532 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2533 ARMConstantPoolValue *CPV = ARMConstantPoolSymbol::Create(
2534 *DAG.getContext(), Sym, ARMPCLabelIndex, PCAdj, ARMCP::GOT_PREL,
2535 /*AddCurrentAddress=*/true);
2536 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2537 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2538 SDValue GOTOffset = DAG.getLoad(
2539 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2541 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2542 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, GOTOffset, PICLabel);
2543 Callee =
2544 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
2546 } else {
2547 // Neither execute-only nor PIC: load the address from a constant pool.
2548 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2549 ARMConstantPoolValue *CPV = ARMConstantPoolSymbol::Create(
2550 *DAG.getContext(), Sym, ARMPCLabelIndex, 0);
2551
2552 // Get the address of the callee into a register
2553 SDValue Addr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2554 Addr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Addr);
2555 Callee = DAG.getLoad(
2556 PtrVt, dl, DAG.getEntryNode(), Addr,
2558 }
2559 }
2560 } else if (isa<GlobalAddressSDNode>(Callee)) {
2561 if (!PreferIndirect) {
2562 isDirect = true;
2563 bool isDef = GVal->isStrongDefinitionForLinker();
2564
2565 // ARM call to a local ARM function is predicable.
2566 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2567 // tBX takes a register source operand.
2568 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2569 assert(TT.isOSBinFormatMachO() && "WrapperPIC use on non-MachO?");
2570 Callee = DAG.getNode(
2571 ARMISD::WrapperPIC, dl, PtrVt,
2572 DAG.getTargetGlobalAddress(GVal, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2573 Callee = DAG.getLoad(
2574 PtrVt, dl, DAG.getEntryNode(), Callee,
2578 } else if (Subtarget->isTargetCOFF()) {
2579 assert(Subtarget->isTargetWindows() &&
2580 "Windows is the only supported COFF target");
2581 unsigned TargetFlags = ARMII::MO_NO_FLAG;
2582 if (GVal->hasDLLImportStorageClass())
2583 TargetFlags = ARMII::MO_DLLIMPORT;
2584 else if (!TM.shouldAssumeDSOLocal(GVal))
2585 TargetFlags = ARMII::MO_COFFSTUB;
2586 Callee = DAG.getTargetGlobalAddress(GVal, dl, PtrVt, /*offset=*/0,
2587 TargetFlags);
2588 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
2589 Callee =
2590 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2591 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2593 } else {
2594 Callee = DAG.getTargetGlobalAddress(GVal, dl, PtrVt, 0, 0);
2595 }
2596 }
2597 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2598 isDirect = true;
2599 // tBX takes a register source operand.
2600 const char *Sym = S->getSymbol();
2601 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2602 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2603 ARMConstantPoolValue *CPV =
2605 ARMPCLabelIndex, 4);
2606 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2607 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2608 Callee = DAG.getLoad(
2609 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2611 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2612 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2613 } else {
2614 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2615 }
2616 }
2617
2618 if (isCmseNSCall) {
2619 assert(!isARMFunc && !isDirect &&
2620 "Cannot handle call to ARM function or direct call");
2621 if (NumBytes > 0) {
2622 DAG.getContext()->diagnose(
2623 DiagnosticInfoUnsupported(DAG.getMachineFunction().getFunction(),
2624 "call to non-secure function would require "
2625 "passing arguments on stack",
2626 dl.getDebugLoc()));
2627 }
2628 if (isStructRet) {
2629 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
2631 "call to non-secure function would return value through pointer",
2632 dl.getDebugLoc()));
2633 }
2634 }
2635
2636 // FIXME: handle tail calls differently.
2637 unsigned CallOpc;
2638 if (Subtarget->isThumb()) {
2639 if (GuardWithBTI)
2640 CallOpc = ARMISD::t2CALL_BTI;
2641 else if (isCmseNSCall)
2642 CallOpc = ARMISD::tSECALL;
2643 else if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2644 CallOpc = ARMISD::CALL_NOLINK;
2645 else
2646 CallOpc = ARMISD::CALL;
2647 } else {
2648 if (!isDirect && !Subtarget->hasV5TOps())
2649 CallOpc = ARMISD::CALL_NOLINK;
2650 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2651 // Emit regular call when code size is the priority
2652 !Subtarget->hasMinSize())
2653 // "mov lr, pc; b _foo" to avoid confusing the RSP
2654 CallOpc = ARMISD::CALL_NOLINK;
2655 else
2656 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2657 }
2658
2659 // We don't usually want to end the call-sequence here because we would tidy
2660 // the frame up *after* the call, however in the ABI-changing tail-call case
2661 // we've carefully laid out the parameters so that when sp is reset they'll be
2662 // in the correct location.
2663 if (isTailCall && !isSibCall) {
2664 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, dl);
2665 InGlue = Chain.getValue(1);
2666 }
2667
2668 std::vector<SDValue> Ops;
2669 Ops.push_back(Chain);
2670 Ops.push_back(Callee);
2671
2672 if (isTailCall) {
2673 Ops.push_back(DAG.getSignedTargetConstant(SPDiff, dl, MVT::i32));
2674 }
2675
2676 // Add argument registers to the end of the list so that they are known live
2677 // into the call.
2678 for (const auto &[Reg, N] : RegsToPass)
2679 Ops.push_back(DAG.getRegister(Reg, N.getValueType()));
2680
2681 // Add a register mask operand representing the call-preserved registers.
2682 const uint32_t *Mask;
2683 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2684 if (isThisReturn) {
2685 // For 'this' returns, use the R0-preserving mask if applicable
2686 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2687 if (!Mask) {
2688 // Set isThisReturn to false if the calling convention is not one that
2689 // allows 'returned' to be modeled in this way, so LowerCallResult does
2690 // not try to pass 'this' straight through
2691 isThisReturn = false;
2692 Mask = ARI->getCallPreservedMask(MF, CallConv);
2693 }
2694 } else
2695 Mask = ARI->getCallPreservedMask(MF, CallConv);
2696
2697 assert(Mask && "Missing call preserved mask for calling convention");
2698 Ops.push_back(DAG.getRegisterMask(Mask));
2699
2700 if (InGlue.getNode())
2701 Ops.push_back(InGlue);
2702
2703 if (isTailCall) {
2705 SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, MVT::Other, Ops);
2706 if (CLI.CFIType)
2707 Ret.getNode()->setCFIType(CLI.CFIType->getZExtValue());
2708 DAG.addNoMergeSiteInfo(Ret.getNode(), CLI.NoMerge);
2709 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
2710 return Ret;
2711 }
2712
2713 // Returns a chain and a flag for retval copy to use.
2714 Chain = DAG.getNode(CallOpc, dl, {MVT::Other, MVT::Glue}, Ops);
2715 if (CLI.CFIType)
2716 Chain.getNode()->setCFIType(CLI.CFIType->getZExtValue());
2717 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
2718 InGlue = Chain.getValue(1);
2719 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
2720
2721 // If we're guaranteeing tail-calls will be honoured, the callee must
2722 // pop its own argument stack on return. But this call is *not* a tail call so
2723 // we need to undo that after it returns to restore the status-quo.
2724 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
2725 uint64_t CalleePopBytes =
2726 canGuaranteeTCO(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : -1U;
2727
2728 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, CalleePopBytes, InGlue, dl);
2729 if (!Ins.empty())
2730 InGlue = Chain.getValue(1);
2731
2732 // Handle result values, copying them out of physregs into vregs that we
2733 // return.
2734 return LowerCallResult(Chain, InGlue, CallConv, isVarArg, Ins, dl, DAG,
2735 InVals, isThisReturn,
2736 isThisReturn ? OutVals[0] : SDValue(), isCmseNSCall);
2737}
2738
2739/// HandleByVal - Every parameter *after* a byval parameter is passed
2740/// on the stack. Remember the next parameter register to allocate,
2741/// and then confiscate the rest of the parameter registers to insure
2742/// this.
2743void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2744 Align Alignment) const {
2745 // Byval (as with any stack) slots are always at least 4 byte aligned.
2746 Alignment = std::max(Alignment, Align(4));
2747
2748 MCRegister Reg = State->AllocateReg(GPRArgRegs);
2749 if (!Reg)
2750 return;
2751
2752 unsigned AlignInRegs = Alignment.value() / 4;
2753 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2754 for (unsigned i = 0; i < Waste; ++i)
2755 Reg = State->AllocateReg(GPRArgRegs);
2756
2757 if (!Reg)
2758 return;
2759
2760 unsigned Excess = 4 * (ARM::R4 - Reg);
2761
2762 // Special case when NSAA != SP and parameter size greater than size of
2763 // all remained GPR regs. In that case we can't split parameter, we must
2764 // send it to stack. We also must set NCRN to R4, so waste all
2765 // remained registers.
2766 const unsigned NSAAOffset = State->getStackSize();
2767 if (NSAAOffset != 0 && Size > Excess) {
2768 while (State->AllocateReg(GPRArgRegs))
2769 ;
2770 return;
2771 }
2772
2773 // First register for byval parameter is the first register that wasn't
2774 // allocated before this method call, so it would be "reg".
2775 // If parameter is small enough to be saved in range [reg, r4), then
2776 // the end (first after last) register would be reg + param-size-in-regs,
2777 // else parameter would be splitted between registers and stack,
2778 // end register would be r4 in this case.
2779 unsigned ByValRegBegin = Reg;
2780 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2781 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2782 // Note, first register is allocated in the beginning of function already,
2783 // allocate remained amount of registers we need.
2784 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2785 State->AllocateReg(GPRArgRegs);
2786 // A byval parameter that is split between registers and memory needs its
2787 // size truncated here.
2788 // In the case where the entire structure fits in registers, we set the
2789 // size in memory to zero.
2790 Size = std::max<int>(Size - Excess, 0);
2791}
2792
2793/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2794/// for tail call optimization. Targets which want to do tail call
2795/// optimization should implement this function. Note that this function also
2796/// processes musttail calls, so when this function returns false on a valid
2797/// musttail call, a fatal backend error occurs.
2798bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2800 SmallVectorImpl<CCValAssign> &ArgLocs, const bool isIndirect) const {
2801 CallingConv::ID CalleeCC = CLI.CallConv;
2802 SDValue Callee = CLI.Callee;
2803 bool isVarArg = CLI.IsVarArg;
2804 const SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2805 const SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2806 const SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2807 const SelectionDAG &DAG = CLI.DAG;
2809 const Function &CallerF = MF.getFunction();
2810 CallingConv::ID CallerCC = CallerF.getCallingConv();
2811
2812 assert(Subtarget->supportsTailCall());
2813
2814 // Indirect tail-calls require a register to hold the target address. That
2815 // register must be:
2816 // * Allocatable (i.e. r0-r7 if the target is Thumb1).
2817 // * Not callee-saved, so must be one of r0-r3 or r12.
2818 // * Not used to hold an argument to the tail-called function, which might be
2819 // in r0-r3.
2820 // * Not used to hold the return address authentication code, which is in r12
2821 // if enabled.
2822 // Sometimes, no register matches all of these conditions, so we can't do a
2823 // tail-call.
2824 if (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect) {
2825 SmallSet<MCPhysReg, 5> AddressRegisters = {ARM::R0, ARM::R1, ARM::R2,
2826 ARM::R3};
2827 if (!(Subtarget->isThumb1Only() ||
2828 MF.getInfo<ARMFunctionInfo>()->shouldSignReturnAddress(true)))
2829 AddressRegisters.insert(ARM::R12);
2830 for (const CCValAssign &AL : ArgLocs)
2831 if (AL.isRegLoc())
2832 AddressRegisters.erase(AL.getLocReg());
2833 if (AddressRegisters.empty()) {
2834 LLVM_DEBUG(dbgs() << "false (no reg to hold function pointer)\n");
2835 return false;
2836 }
2837 }
2838
2839 // Look for obvious safe cases to perform tail call optimization that do not
2840 // require ABI changes. This is what gcc calls sibcall.
2841
2842 // Exception-handling functions need a special set of instructions to indicate
2843 // a return to the hardware. Tail-calling another function would probably
2844 // break this.
2845 if (CallerF.hasFnAttribute("interrupt")) {
2846 LLVM_DEBUG(dbgs() << "false (interrupt attribute)\n");
2847 return false;
2848 }
2849
2850 if (canGuaranteeTCO(CalleeCC,
2851 getTargetMachine().Options.GuaranteedTailCallOpt)) {
2852 LLVM_DEBUG(dbgs() << (CalleeCC == CallerCC ? "true" : "false")
2853 << " (guaranteed tail-call CC)\n");
2854 return CalleeCC == CallerCC;
2855 }
2856
2857 // Also avoid sibcall optimization if either caller or callee uses struct
2858 // return semantics.
2859 bool isCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
2860 bool isCallerStructRet = MF.getFunction().hasStructRetAttr();
2861 if (isCalleeStructRet != isCallerStructRet) {
2862 LLVM_DEBUG(dbgs() << "false (struct-ret)\n");
2863 return false;
2864 }
2865
2866 // Externally-defined functions with weak linkage should not be
2867 // tail-called on ARM when the OS does not support dynamic
2868 // pre-emption of symbols, as the AAELF spec requires normal calls
2869 // to undefined weak functions to be replaced with a NOP or jump to the
2870 // next instruction. The behaviour of branch instructions in this
2871 // situation (as used for tail calls) is implementation-defined, so we
2872 // cannot rely on the linker replacing the tail call with a return.
2873 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2874 const GlobalValue *GV = G->getGlobal();
2875 const Triple &TT = GV->getParent()->getTargetTriple();
2876 if (GV->hasExternalWeakLinkage() &&
2877 (!TT.isOSWindows() || TT.isOSBinFormatELF() ||
2878 TT.isOSBinFormatMachO())) {
2879 LLVM_DEBUG(dbgs() << "false (external weak linkage)\n");
2880 return false;
2881 }
2882 }
2883
2884 // Check that the call results are passed in the same way.
2885 LLVMContext &C = *DAG.getContext();
2887 getEffectiveCallingConv(CalleeCC, isVarArg),
2888 getEffectiveCallingConv(CallerCC, CallerF.isVarArg()), MF, C, Ins,
2889 CCAssignFnForReturn(CalleeCC, isVarArg),
2890 CCAssignFnForReturn(CallerCC, CallerF.isVarArg()))) {
2891 LLVM_DEBUG(dbgs() << "false (incompatible results)\n");
2892 return false;
2893 }
2894 // The callee has to preserve all registers the caller needs to preserve.
2895 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2896 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2897 if (CalleeCC != CallerCC) {
2898 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2899 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) {
2900 LLVM_DEBUG(dbgs() << "false (not all registers preserved)\n");
2901 return false;
2902 }
2903 }
2904
2905 // If Caller's vararg argument has been split between registers and stack, do
2906 // not perform tail call, since part of the argument is in caller's local
2907 // frame.
2908 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2909 if (CLI.IsVarArg && AFI_Caller->getArgRegsSaveSize()) {
2910 LLVM_DEBUG(dbgs() << "false (arg reg save area)\n");
2911 return false;
2912 }
2913
2914 // If the callee takes no arguments then go on to check the results of the
2915 // call.
2916 const MachineRegisterInfo &MRI = MF.getRegInfo();
2917 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) {
2918 LLVM_DEBUG(dbgs() << "false (parameters in CSRs do not match)\n");
2919 return false;
2920 }
2921
2922 // If the stack arguments for this call do not fit into our own save area then
2923 // the call cannot be made tail.
2924 if (CCInfo.getStackSize() > AFI_Caller->getArgumentStackSize())
2925 return false;
2926
2927 LLVM_DEBUG(dbgs() << "true\n");
2928 return true;
2929}
2930
2931bool
2932ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2933 MachineFunction &MF, bool isVarArg,
2935 LLVMContext &Context, const Type *RetTy) const {
2937 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2938 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2939}
2940
2942 const SDLoc &DL, SelectionDAG &DAG) {
2943 const MachineFunction &MF = DAG.getMachineFunction();
2944 const Function &F = MF.getFunction();
2945
2946 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2947
2948 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2949 // version of the "preferred return address". These offsets affect the return
2950 // instruction if this is a return from PL1 without hypervisor extensions.
2951 // IRQ/FIQ: +4 "subs pc, lr, #4"
2952 // SWI: 0 "subs pc, lr, #0"
2953 // ABORT: +4 "subs pc, lr, #4"
2954 // UNDEF: +4/+2 "subs pc, lr, #0"
2955 // UNDEF varies depending on where the exception came from ARM or Thumb
2956 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2957
2958 int64_t LROffset;
2959 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2960 IntKind == "ABORT")
2961 LROffset = 4;
2962 else if (IntKind == "SWI" || IntKind == "UNDEF")
2963 LROffset = 0;
2964 else
2965 report_fatal_error("Unsupported interrupt attribute. If present, value "
2966 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2967
2968 RetOps.insert(RetOps.begin() + 1,
2969 DAG.getConstant(LROffset, DL, MVT::i32, false));
2970
2971 return DAG.getNode(ARMISD::INTRET_GLUE, DL, MVT::Other, RetOps);
2972}
2973
2974SDValue
2975ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2976 bool isVarArg,
2978 const SmallVectorImpl<SDValue> &OutVals,
2979 const SDLoc &dl, SelectionDAG &DAG) const {
2980 // CCValAssign - represent the assignment of the return value to a location.
2982
2983 // CCState - Info about the registers and stack slots.
2984 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2985 *DAG.getContext());
2986
2987 // Analyze outgoing return values.
2988 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2989
2990 SDValue Glue;
2992 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2993 bool isLittleEndian = Subtarget->isLittle();
2994
2996 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2997 AFI->setReturnRegsCount(RVLocs.size());
2998
2999 // Report error if cmse entry function returns structure through first ptr arg.
3000 if (AFI->isCmseNSEntryFunction() && MF.getFunction().hasStructRetAttr()) {
3001 // Note: using an empty SDLoc(), as the first line of the function is a
3002 // better place to report than the last line.
3003 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
3005 "secure entry function would return value through pointer",
3006 SDLoc().getDebugLoc()));
3007 }
3008
3009 // Copy the result values into the output registers.
3010 for (unsigned i = 0, realRVLocIdx = 0;
3011 i != RVLocs.size();
3012 ++i, ++realRVLocIdx) {
3013 CCValAssign &VA = RVLocs[i];
3014 assert(VA.isRegLoc() && "Can only return in registers!");
3015
3016 SDValue Arg = OutVals[realRVLocIdx];
3017 bool ReturnF16 = false;
3018
3019 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
3020 // Half-precision return values can be returned like this:
3021 //
3022 // t11 f16 = fadd ...
3023 // t12: i16 = bitcast t11
3024 // t13: i32 = zero_extend t12
3025 // t14: f32 = bitcast t13 <~~~~~~~ Arg
3026 //
3027 // to avoid code generation for bitcasts, we simply set Arg to the node
3028 // that produces the f16 value, t11 in this case.
3029 //
3030 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
3031 SDValue ZE = Arg.getOperand(0);
3032 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
3033 SDValue BC = ZE.getOperand(0);
3034 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
3035 Arg = BC.getOperand(0);
3036 ReturnF16 = true;
3037 }
3038 }
3039 }
3040 }
3041
3042 switch (VA.getLocInfo()) {
3043 default: llvm_unreachable("Unknown loc info!");
3044 case CCValAssign::Full: break;
3045 case CCValAssign::BCvt:
3046 if (!ReturnF16)
3047 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3048 break;
3049 }
3050
3051 // Mask f16 arguments if this is a CMSE nonsecure entry.
3052 auto RetVT = Outs[realRVLocIdx].ArgVT;
3053 if (AFI->isCmseNSEntryFunction() && (RetVT == MVT::f16)) {
3054 if (VA.needsCustom() && VA.getValVT() == MVT::f16) {
3055 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
3056 } else {
3057 auto LocBits = VA.getLocVT().getSizeInBits();
3058 auto MaskValue = APInt::getLowBitsSet(LocBits, RetVT.getSizeInBits());
3059 SDValue Mask =
3060 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
3061 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
3062 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
3063 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3064 }
3065 }
3066
3067 if (VA.needsCustom() &&
3068 (VA.getLocVT() == MVT::v2f64 || VA.getLocVT() == MVT::f64)) {
3069 if (VA.getLocVT() == MVT::v2f64) {
3070 // Extract the first half and return it in two registers.
3071 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3072 DAG.getConstant(0, dl, MVT::i32));
3073 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
3074 DAG.getVTList(MVT::i32, MVT::i32), Half);
3075
3076 Chain =
3077 DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3078 HalfGPRs.getValue(isLittleEndian ? 0 : 1), Glue);
3079 Glue = Chain.getValue(1);
3080 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3081 VA = RVLocs[++i]; // skip ahead to next loc
3082 Chain =
3083 DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3084 HalfGPRs.getValue(isLittleEndian ? 1 : 0), Glue);
3085 Glue = Chain.getValue(1);
3086 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3087 VA = RVLocs[++i]; // skip ahead to next loc
3088
3089 // Extract the 2nd half and fall through to handle it as an f64 value.
3090 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3091 DAG.getConstant(1, dl, MVT::i32));
3092 }
3093 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
3094 // available.
3095 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
3096 DAG.getVTList(MVT::i32, MVT::i32), Arg);
3097 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3098 fmrrd.getValue(isLittleEndian ? 0 : 1), Glue);
3099 Glue = Chain.getValue(1);
3100 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3101 VA = RVLocs[++i]; // skip ahead to next loc
3102 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3103 fmrrd.getValue(isLittleEndian ? 1 : 0), Glue);
3104 } else
3105 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Glue);
3106
3107 // Guarantee that all emitted copies are
3108 // stuck together, avoiding something bad.
3109 Glue = Chain.getValue(1);
3110 RetOps.push_back(DAG.getRegister(
3111 VA.getLocReg(), ReturnF16 ? Arg.getValueType() : VA.getLocVT()));
3112 }
3113 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
3114 const MCPhysReg *I =
3115 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3116 if (I) {
3117 for (; *I; ++I) {
3118 if (ARM::GPRRegClass.contains(*I))
3119 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
3120 else if (ARM::DPRRegClass.contains(*I))
3122 else
3123 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3124 }
3125 }
3126
3127 // Update chain and glue.
3128 RetOps[0] = Chain;
3129 if (Glue.getNode())
3130 RetOps.push_back(Glue);
3131
3132 // CPUs which aren't M-class use a special sequence to return from
3133 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
3134 // though we use "subs pc, lr, #N").
3135 //
3136 // M-class CPUs actually use a normal return sequence with a special
3137 // (hardware-provided) value in LR, so the normal code path works.
3138 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
3139 !Subtarget->isMClass()) {
3140 if (Subtarget->isThumb1Only())
3141 report_fatal_error("interrupt attribute is not supported in Thumb1");
3142 return LowerInterruptReturn(RetOps, dl, DAG);
3143 }
3144
3145 unsigned RetNode =
3146 AFI->isCmseNSEntryFunction() ? ARMISD::SERET_GLUE : ARMISD::RET_GLUE;
3147 return DAG.getNode(RetNode, dl, MVT::Other, RetOps);
3148}
3149
3150bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
3151 if (N->getNumValues() != 1)
3152 return false;
3153 if (!N->hasNUsesOfValue(1, 0))
3154 return false;
3155
3156 SDValue TCChain = Chain;
3157 SDNode *Copy = *N->user_begin();
3158 if (Copy->getOpcode() == ISD::CopyToReg) {
3159 // If the copy has a glue operand, we conservatively assume it isn't safe to
3160 // perform a tail call.
3161 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3162 return false;
3163 TCChain = Copy->getOperand(0);
3164 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
3165 SDNode *VMov = Copy;
3166 // f64 returned in a pair of GPRs.
3167 SmallPtrSet<SDNode*, 2> Copies;
3168 for (SDNode *U : VMov->users()) {
3169 if (U->getOpcode() != ISD::CopyToReg)
3170 return false;
3171 Copies.insert(U);
3172 }
3173 if (Copies.size() > 2)
3174 return false;
3175
3176 for (SDNode *U : VMov->users()) {
3177 SDValue UseChain = U->getOperand(0);
3178 if (Copies.count(UseChain.getNode()))
3179 // Second CopyToReg
3180 Copy = U;
3181 else {
3182 // We are at the top of this chain.
3183 // If the copy has a glue operand, we conservatively assume it
3184 // isn't safe to perform a tail call.
3185 if (U->getOperand(U->getNumOperands() - 1).getValueType() == MVT::Glue)
3186 return false;
3187 // First CopyToReg
3188 TCChain = UseChain;
3189 }
3190 }
3191 } else if (Copy->getOpcode() == ISD::BITCAST) {
3192 // f32 returned in a single GPR.
3193 if (!Copy->hasOneUse())
3194 return false;
3195 Copy = *Copy->user_begin();
3196 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
3197 return false;
3198 // If the copy has a glue operand, we conservatively assume it isn't safe to
3199 // perform a tail call.
3200 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3201 return false;
3202 TCChain = Copy->getOperand(0);
3203 } else {
3204 return false;
3205 }
3206
3207 bool HasRet = false;
3208 for (const SDNode *U : Copy->users()) {
3209 if (U->getOpcode() != ARMISD::RET_GLUE &&
3210 U->getOpcode() != ARMISD::INTRET_GLUE)
3211 return false;
3212 HasRet = true;
3213 }
3214
3215 if (!HasRet)
3216 return false;
3217
3218 Chain = TCChain;
3219 return true;
3220}
3221
3222bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3223 if (!Subtarget->supportsTailCall())
3224 return false;
3225
3226 if (!CI->isTailCall())
3227 return false;
3228
3229 return true;
3230}
3231
3232// Trying to write a 64 bit value so need to split into two 32 bit values first,
3233// and pass the lower and high parts through.
3235 SDLoc DL(Op);
3236 SDValue WriteValue = Op->getOperand(2);
3237
3238 // This function is only supposed to be called for i64 type argument.
3239 assert(WriteValue.getValueType() == MVT::i64
3240 && "LowerWRITE_REGISTER called for non-i64 type argument.");
3241
3242 SDValue Lo, Hi;
3243 std::tie(Lo, Hi) = DAG.SplitScalar(WriteValue, DL, MVT::i32, MVT::i32);
3244 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
3245 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
3246}
3247
3248// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3249// their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
3250// one of the above mentioned nodes. It has to be wrapped because otherwise
3251// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3252// be used to form addressing mode. These wrapped nodes will be selected
3253// into MOVi.
3254SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
3255 SelectionDAG &DAG) const {
3256 EVT PtrVT = Op.getValueType();
3257 // FIXME there is no actual debug info here
3258 SDLoc dl(Op);
3259 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3260 SDValue Res;
3261
3262 // When generating execute-only code Constant Pools must be promoted to the
3263 // global data section. It's a bit ugly that we can't share them across basic
3264 // blocks, but this way we guarantee that execute-only behaves correct with
3265 // position-independent addressing modes.
3266 if (Subtarget->genExecuteOnly()) {
3267 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3268 auto *T = CP->getType();
3269 auto C = const_cast<Constant*>(CP->getConstVal());
3270 auto M = DAG.getMachineFunction().getFunction().getParent();
3271 auto GV = new GlobalVariable(
3272 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
3273 Twine(DAG.getDataLayout().getInternalSymbolPrefix()) + "CP" +
3274 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
3275 Twine(AFI->createPICLabelUId()));
3276 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3277 return LowerGlobalAddress(GA, DAG);
3278 }
3279
3280 // The 16-bit ADR instruction can only encode offsets that are multiples of 4,
3281 // so we need to align to at least 4 bytes when we don't have 32-bit ADR.
3282 Align CPAlign = CP->getAlign();
3283 if (Subtarget->isThumb1Only())
3284 CPAlign = std::max(CPAlign, Align(4));
3286 Res =
3287 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CPAlign);
3288 else
3289 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CPAlign);
3290 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
3291}
3292
3294 // If we don't have a 32-bit pc-relative branch instruction then the jump
3295 // table consists of block addresses. Usually this is inline, but for
3296 // execute-only it must be placed out-of-line.
3297 if (Subtarget->genExecuteOnly() && !Subtarget->hasV8MBaselineOps())
3300}
3301
3302SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
3303 SelectionDAG &DAG) const {
3306 unsigned ARMPCLabelIndex = 0;
3307 SDLoc DL(Op);
3308 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3309 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3310 SDValue CPAddr;
3311 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3312 if (!IsPositionIndependent) {
3313 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, Align(4));
3314 } else {
3315 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3316 ARMPCLabelIndex = AFI->createPICLabelUId();
3318 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3319 ARMCP::CPBlockAddress, PCAdj);
3320 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3321 }
3322 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3323 SDValue Result = DAG.getLoad(
3324 PtrVT, DL, DAG.getEntryNode(), CPAddr,
3326 if (!IsPositionIndependent)
3327 return Result;
3328 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3329 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3330}
3331
3332/// Convert a TLS address reference into the correct sequence of loads
3333/// and calls to compute the variable's address for Darwin, and return an
3334/// SDValue containing the final node.
3335
3336/// Darwin only has one TLS scheme which must be capable of dealing with the
3337/// fully general situation, in the worst case. This means:
3338/// + "extern __thread" declaration.
3339/// + Defined in a possibly unknown dynamic library.
3340///
3341/// The general system is that each __thread variable has a [3 x i32] descriptor
3342/// which contains information used by the runtime to calculate the address. The
3343/// only part of this the compiler needs to know about is the first word, which
3344/// contains a function pointer that must be called with the address of the
3345/// entire descriptor in "r0".
3346///
3347/// Since this descriptor may be in a different unit, in general access must
3348/// proceed along the usual ARM rules. A common sequence to produce is:
3349///
3350/// movw rT1, :lower16:_var$non_lazy_ptr
3351/// movt rT1, :upper16:_var$non_lazy_ptr
3352/// ldr r0, [rT1]
3353/// ldr rT2, [r0]
3354/// blx rT2
3355/// [...address now in r0...]
3356SDValue
3357ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3358 SelectionDAG &DAG) const {
3359 assert(getTargetMachine().getTargetTriple().isOSDarwin() &&
3360 "This function expects a Darwin target");
3361 SDLoc DL(Op);
3362
3363 // First step is to get the address of the actua global symbol. This is where
3364 // the TLS descriptor lives.
3365 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3366
3367 // The first entry in the descriptor is a function pointer that we must call
3368 // to obtain the address of the variable.
3369 SDValue Chain = DAG.getEntryNode();
3370 SDValue FuncTLVGet = DAG.getLoad(
3371 MVT::i32, DL, Chain, DescAddr,
3375 Chain = FuncTLVGet.getValue(1);
3376
3378 MachineFrameInfo &MFI = F.getFrameInfo();
3379 MFI.setAdjustsStack(true);
3380
3381 // TLS calls preserve all registers except those that absolutely must be
3382 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3383 // silly).
3384 auto TRI =
3386 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3387 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3388
3389 // Finally, we can make the call. This is just a degenerate version of a
3390 // normal AArch64 call node: r0 takes the address of the descriptor, and
3391 // returns the address of the variable in this thread.
3392 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3393 Chain =
3394 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3395 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3396 DAG.getRegisterMask(Mask), Chain.getValue(1));
3397 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3398}
3399
3400SDValue
3401ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3402 SelectionDAG &DAG) const {
3403 assert(getTargetMachine().getTargetTriple().isOSWindows() &&
3404 "Windows specific TLS lowering");
3405
3406 SDValue Chain = DAG.getEntryNode();
3407 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3408 SDLoc DL(Op);
3409
3410 // Load the current TEB (thread environment block)
3411 SDValue Ops[] = {Chain,
3412 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3413 DAG.getTargetConstant(15, DL, MVT::i32),
3414 DAG.getTargetConstant(0, DL, MVT::i32),
3415 DAG.getTargetConstant(13, DL, MVT::i32),
3416 DAG.getTargetConstant(0, DL, MVT::i32),
3417 DAG.getTargetConstant(2, DL, MVT::i32)};
3418 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3419 DAG.getVTList(MVT::i32, MVT::Other), Ops);
3420
3421 SDValue TEB = CurrentTEB.getValue(0);
3422 Chain = CurrentTEB.getValue(1);
3423
3424 // Load the ThreadLocalStoragePointer from the TEB
3425 // A pointer to the TLS array is located at offset 0x2c from the TEB.
3426 SDValue TLSArray =
3427 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3428 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3429
3430 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3431 // offset into the TLSArray.
3432
3433 // Load the TLS index from the C runtime
3434 SDValue TLSIndex =
3435 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3436 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3437 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3438
3439 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3440 DAG.getConstant(2, DL, MVT::i32));
3441 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3442 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3443 MachinePointerInfo());
3444
3445 // Get the offset of the start of the .tls section (section base)
3446 const auto *GA = cast<GlobalAddressSDNode>(Op);
3447 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3448 SDValue Offset = DAG.getLoad(
3449 PtrVT, DL, Chain,
3450 DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3451 DAG.getTargetConstantPool(CPV, PtrVT, Align(4))),
3453
3454 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3455}
3456
3457// Lower ISD::GlobalTLSAddress using the "general dynamic" model
3458SDValue
3459ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3460 SelectionDAG &DAG) const {
3461 SDLoc dl(GA);
3462 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3463 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3465 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3466 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3467 ARMConstantPoolValue *CPV =
3468 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3469 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3470 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3471 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3472 Argument = DAG.getLoad(
3473 PtrVT, dl, DAG.getEntryNode(), Argument,
3475 SDValue Chain = Argument.getValue(1);
3476
3477 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3478 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3479
3480 // call __tls_get_addr.
3482 Args.emplace_back(Argument, Type::getInt32Ty(*DAG.getContext()));
3483
3484 // FIXME: is there useful debug info available here?
3485 TargetLowering::CallLoweringInfo CLI(DAG);
3486 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3488 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3489
3490 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3491 return CallResult.first;
3492}
3493
3494// Lower ISD::GlobalTLSAddress using the "initial exec" or
3495// "local exec" model.
3496SDValue
3497ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3498 SelectionDAG &DAG,
3499 TLSModel::Model model) const {
3500 const GlobalValue *GV = GA->getGlobal();
3501 SDLoc dl(GA);
3503 SDValue Chain = DAG.getEntryNode();
3504 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3505 // Get the Thread Pointer
3506 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3507
3508 if (model == TLSModel::InitialExec) {
3510 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3511 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3512 // Initial exec model.
3513 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3514 ARMConstantPoolValue *CPV =
3515 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3517 true);
3518 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3519 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3520 Offset = DAG.getLoad(
3521 PtrVT, dl, Chain, Offset,
3523 Chain = Offset.getValue(1);
3524
3525 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3526 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3527
3528 Offset = DAG.getLoad(
3529 PtrVT, dl, Chain, Offset,
3531 } else {
3532 // local exec model
3533 assert(model == TLSModel::LocalExec);
3534 ARMConstantPoolValue *CPV =
3536 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3537 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3538 Offset = DAG.getLoad(
3539 PtrVT, dl, Chain, Offset,
3541 }
3542
3543 // The address of the thread local variable is the add of the thread
3544 // pointer with the offset of the variable.
3545 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3546}
3547
3548SDValue
3549ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3550 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3551 if (DAG.getTarget().useEmulatedTLS())
3552 return LowerToTLSEmulatedModel(GA, DAG);
3553
3554 const Triple &TT = getTargetMachine().getTargetTriple();
3555 if (TT.isOSDarwin())
3556 return LowerGlobalTLSAddressDarwin(Op, DAG);
3557
3558 if (TT.isOSWindows())
3559 return LowerGlobalTLSAddressWindows(Op, DAG);
3560
3561 // TODO: implement the "local dynamic" model
3562 assert(TT.isOSBinFormatELF() && "Only ELF implemented here");
3564
3565 switch (model) {
3568 return LowerToTLSGeneralDynamicModel(GA, DAG);
3571 return LowerToTLSExecModels(GA, DAG, model);
3572 }
3573 llvm_unreachable("bogus TLS model");
3574}
3575
3576/// Return true if all users of V are within function F, looking through
3577/// ConstantExprs.
3578static bool allUsersAreInFunction(const Value *V, const Function *F) {
3579 SmallVector<const User*,4> Worklist(V->users());
3580 while (!Worklist.empty()) {
3581 auto *U = Worklist.pop_back_val();
3582 if (isa<ConstantExpr>(U)) {
3583 append_range(Worklist, U->users());
3584 continue;
3585 }
3586
3587 auto *I = dyn_cast<Instruction>(U);
3588 if (!I || I->getParent()->getParent() != F)
3589 return false;
3590 }
3591 return true;
3592}
3593
3595 const GlobalValue *GV, SelectionDAG &DAG,
3596 EVT PtrVT, const SDLoc &dl) {
3597 // If we're creating a pool entry for a constant global with unnamed address,
3598 // and the global is small enough, we can emit it inline into the constant pool
3599 // to save ourselves an indirection.
3600 //
3601 // This is a win if the constant is only used in one function (so it doesn't
3602 // need to be duplicated) or duplicating the constant wouldn't increase code
3603 // size (implying the constant is no larger than 4 bytes).
3604 const Function &F = DAG.getMachineFunction().getFunction();
3605
3606 // We rely on this decision to inline being idempotent and unrelated to the
3607 // use-site. We know that if we inline a variable at one use site, we'll
3608 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3609 // doesn't know about this optimization, so bail out if it's enabled else
3610 // we could decide to inline here (and thus never emit the GV) but require
3611 // the GV from fast-isel generated code.
3614 return SDValue();
3615
3616 auto *GVar = dyn_cast<GlobalVariable>(GV);
3617 if (!GVar || !GVar->hasInitializer() ||
3618 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3619 !GVar->hasLocalLinkage())
3620 return SDValue();
3621
3622 // If we inline a value that contains relocations, we move the relocations
3623 // from .data to .text. This is not allowed in position-independent code.
3624 auto *Init = GVar->getInitializer();
3625 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3626 Init->needsDynamicRelocation())
3627 return SDValue();
3628
3629 // The constant islands pass can only really deal with alignment requests
3630 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3631 // any type wanting greater alignment requirements than 4 bytes. We also
3632 // can only promote constants that are multiples of 4 bytes in size or
3633 // are paddable to a multiple of 4. Currently we only try and pad constants
3634 // that are strings for simplicity.
3635 auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3636 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3637 Align PrefAlign = DAG.getDataLayout().getPreferredAlign(GVar);
3638 unsigned RequiredPadding = 4 - (Size % 4);
3639 bool PaddingPossible =
3640 RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3641 if (!PaddingPossible || PrefAlign > 4 || Size > ConstpoolPromotionMaxSize ||
3642 Size == 0)
3643 return SDValue();
3644
3645 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3647 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3648
3649 // We can't bloat the constant pool too much, else the ConstantIslands pass
3650 // may fail to converge. If we haven't promoted this global yet (it may have
3651 // multiple uses), and promoting it would increase the constant pool size (Sz
3652 // > 4), ensure we have space to do so up to MaxTotal.
3653 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3654 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3656 return SDValue();
3657
3658 // This is only valid if all users are in a single function; we can't clone
3659 // the constant in general. The LLVM IR unnamed_addr allows merging
3660 // constants, but not cloning them.
3661 //
3662 // We could potentially allow cloning if we could prove all uses of the
3663 // constant in the current function don't care about the address, like
3664 // printf format strings. But that isn't implemented for now.
3665 if (!allUsersAreInFunction(GVar, &F))
3666 return SDValue();
3667
3668 // We're going to inline this global. Pad it out if needed.
3669 if (RequiredPadding != 4) {
3670 StringRef S = CDAInit->getAsString();
3671
3673 std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3674 while (RequiredPadding--)
3675 V.push_back(0);
3677 }
3678
3679 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3680 SDValue CPAddr = DAG.getTargetConstantPool(CPVal, PtrVT, Align(4));
3681 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3684 PaddedSize - 4);
3685 }
3686 ++NumConstpoolPromoted;
3687 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3688}
3689
3691 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3692 if (!(GV = GA->getAliaseeObject()))
3693 return false;
3694 if (const auto *V = dyn_cast<GlobalVariable>(GV))
3695 return V->isConstant();
3696 return isa<Function>(GV);
3697}
3698
3699SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3700 SelectionDAG &DAG) const {
3701 switch (Subtarget->getTargetTriple().getObjectFormat()) {
3702 default: llvm_unreachable("unknown object format");
3703 case Triple::COFF:
3704 return LowerGlobalAddressWindows(Op, DAG);
3705 case Triple::ELF:
3706 return LowerGlobalAddressELF(Op, DAG);
3707 case Triple::MachO:
3708 return LowerGlobalAddressDarwin(Op, DAG);
3709 }
3710}
3711
3712SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3713 SelectionDAG &DAG) const {
3714 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3715 SDLoc dl(Op);
3716 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3717 bool IsRO = isReadOnly(GV);
3718
3719 // promoteToConstantPool only if not generating XO text section
3720 if (GV->isDSOLocal() && !Subtarget->genExecuteOnly())
3721 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3722 return V;
3723
3724 if (isPositionIndependent()) {
3726 GV, dl, PtrVT, 0, GV->isDSOLocal() ? 0 : ARMII::MO_GOT);
3727 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3728 if (!GV->isDSOLocal())
3729 Result =
3730 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3732 return Result;
3733 } else if (Subtarget->isROPI() && IsRO) {
3734 // PC-relative.
3735 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3736 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3737 return Result;
3738 } else if (Subtarget->isRWPI() && !IsRO) {
3739 // SB-relative.
3740 SDValue RelAddr;
3741 if (Subtarget->useMovt()) {
3742 ++NumMovwMovt;
3743 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3744 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3745 } else { // use literal pool for address constant
3746 ARMConstantPoolValue *CPV =
3748 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3749 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3750 RelAddr = DAG.getLoad(
3751 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3753 }
3754 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3755 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3756 return Result;
3757 }
3758
3759 // If we have T2 ops, we can materialize the address directly via movt/movw
3760 // pair. This is always cheaper. If need to generate Execute Only code, and we
3761 // only have Thumb1 available, we can't use a constant pool and are forced to
3762 // use immediate relocations.
3763 if (Subtarget->useMovt() || Subtarget->genExecuteOnly()) {
3764 if (Subtarget->useMovt())
3765 ++NumMovwMovt;
3766 // FIXME: Once remat is capable of dealing with instructions with register
3767 // operands, expand this into two nodes.
3768 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3769 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3770 } else {
3771 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, Align(4));
3772 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3773 return DAG.getLoad(
3774 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3776 }
3777}
3778
3779SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3780 SelectionDAG &DAG) const {
3781 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3782 "ROPI/RWPI not currently supported for Darwin");
3783 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3784 SDLoc dl(Op);
3785 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3786
3787 if (Subtarget->useMovt())
3788 ++NumMovwMovt;
3789
3790 // FIXME: Once remat is capable of dealing with instructions with register
3791 // operands, expand this into multiple nodes
3792 unsigned Wrapper =
3793 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3794
3795 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3796 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3797
3798 if (Subtarget->isGVIndirectSymbol(GV))
3799 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3801 return Result;
3802}
3803
3804SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3805 SelectionDAG &DAG) const {
3806 assert(getTargetMachine().getTargetTriple().isOSWindows() &&
3807 "non-Windows COFF is not supported");
3808 assert(Subtarget->useMovt() &&
3809 "Windows on ARM expects to use movw/movt");
3810 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3811 "ROPI/RWPI not currently supported for Windows");
3812
3813 const TargetMachine &TM = getTargetMachine();
3814 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3815 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3816 if (GV->hasDLLImportStorageClass())
3817 TargetFlags = ARMII::MO_DLLIMPORT;
3818 else if (!TM.shouldAssumeDSOLocal(GV))
3819 TargetFlags = ARMII::MO_COFFSTUB;
3820 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3822 SDLoc DL(Op);
3823
3824 ++NumMovwMovt;
3825
3826 // FIXME: Once remat is capable of dealing with instructions with register
3827 // operands, expand this into two nodes.
3828 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3829 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3830 TargetFlags));
3831 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3832 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3834 return Result;
3835}
3836
3837SDValue
3838ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3839 SDLoc dl(Op);
3840 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3841 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3842 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3843 Op.getOperand(1), Val);
3844}
3845
3846SDValue
3847ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3848 SDLoc dl(Op);
3849 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3850 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3851}
3852
3853SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3854 SelectionDAG &DAG) const {
3855 SDLoc dl(Op);
3856 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3857 Op.getOperand(0));
3858}
3859
3860SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3861 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3862 unsigned IntNo =
3863 Op.getConstantOperandVal(Op.getOperand(0).getValueType() == MVT::Other);
3864 switch (IntNo) {
3865 default:
3866 return SDValue(); // Don't custom lower most intrinsics.
3867 case Intrinsic::arm_gnu_eabi_mcount: {
3869 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3870 SDLoc dl(Op);
3871 SDValue Chain = Op.getOperand(0);
3872 // call "\01__gnu_mcount_nc"
3873 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3874 const uint32_t *Mask =
3876 assert(Mask && "Missing call preserved mask for calling convention");
3877 // Mark LR an implicit live-in.
3878 Register Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3879 SDValue ReturnAddress =
3880 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
3881 constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue};
3882 SDValue Callee =
3883 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
3885 if (Subtarget->isThumb())
3886 return SDValue(
3887 DAG.getMachineNode(
3888 ARM::tBL_PUSHLR, dl, ResultTys,
3889 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
3890 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
3891 0);
3892 return SDValue(
3893 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
3894 {ReturnAddress, Callee, RegisterMask, Chain}),
3895 0);
3896 }
3897 }
3898}
3899
3900SDValue
3901ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3902 const ARMSubtarget *Subtarget) const {
3903 unsigned IntNo = Op.getConstantOperandVal(0);
3904 SDLoc dl(Op);
3905 switch (IntNo) {
3906 default: return SDValue(); // Don't custom lower most intrinsics.
3907 case Intrinsic::localaddress: {
3908 const MachineFunction &MF = DAG.getMachineFunction();
3909 const auto *RegInfo = Subtarget->getRegisterInfo();
3910 unsigned Reg = RegInfo->getLocalAddressRegister(MF);
3911 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
3912 Op.getSimpleValueType());
3913 }
3914 case Intrinsic::eh_recoverfp: {
3915 SDValue FnOp = Op.getOperand(1);
3916 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
3917 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
3918 if (!Fn)
3920 "llvm.eh.recoverfp must take a function as the first argument");
3921 const auto *RegInfo = Subtarget->getRegisterInfo();
3922 Register BaseReg = RegInfo->getBaseRegister();
3924 MachineBasicBlock &MBB = *MF.begin();
3925 if (!MBB.isLiveIn(BaseReg))
3926 MBB.addLiveIn(BaseReg);
3927 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3928 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, BaseReg, PtrVT);
3929 }
3930 case Intrinsic::thread_pointer: {
3931 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3932 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3933 }
3934 case Intrinsic::arm_cls: {
3935 // Note: arm_cls and arm_cls64 intrinsics are expanded directly here
3936 // in LowerINTRINSIC_WO_CHAIN since there's no native scalar CLS
3937 // instruction.
3938 const SDValue &Operand = Op.getOperand(1);
3939 const EVT VTy = Op.getValueType();
3940 return DAG.getNode(ISD::CTLS, dl, VTy, Operand);
3941 }
3942 case Intrinsic::arm_cls64: {
3943 // arm_cls64 returns i32 but takes i64 input.
3944 // Use ISD::CTLS for i64 and truncate the result.
3945 SDValue CTLS64 = DAG.getNode(ISD::CTLS, dl, MVT::i64, Op.getOperand(1));
3946 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, CTLS64);
3947 }
3948 case Intrinsic::arm_neon_vcls:
3949 case Intrinsic::arm_mve_vcls: {
3950 // Lower vector CLS intrinsics to ISD::CTLS.
3951 // Vector CTLS is Legal when NEON/MVE is available (set elsewhere).
3952 const EVT VTy = Op.getValueType();
3953 return DAG.getNode(ISD::CTLS, dl, VTy, Op.getOperand(1));
3954 }
3955 case Intrinsic::eh_sjlj_lsda: {
3957 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3958 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3959 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3960 SDValue CPAddr;
3961 bool IsPositionIndependent = isPositionIndependent();
3962 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3963 ARMConstantPoolValue *CPV =
3964 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3965 ARMCP::CPLSDA, PCAdj);
3966 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3967 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3968 SDValue Result = DAG.getLoad(
3969 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3971
3972 if (IsPositionIndependent) {
3973 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3974 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3975 }
3976 return Result;
3977 }
3978 case Intrinsic::arm_neon_vabs:
3979 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3980 Op.getOperand(1));
3981 case Intrinsic::arm_neon_vabds:
3982 if (Op.getValueType().isInteger())
3983 return DAG.getNode(ISD::ABDS, SDLoc(Op), Op.getValueType(),
3984 Op.getOperand(1), Op.getOperand(2));
3985 return SDValue();
3986 case Intrinsic::arm_neon_vabdu:
3987 return DAG.getNode(ISD::ABDU, SDLoc(Op), Op.getValueType(),
3988 Op.getOperand(1), Op.getOperand(2));
3989 case Intrinsic::arm_neon_vmulls:
3990 case Intrinsic::arm_neon_vmullu: {
3991 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3992 ? ARMISD::VMULLs : ARMISD::VMULLu;
3993 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3994 Op.getOperand(1), Op.getOperand(2));
3995 }
3996 case Intrinsic::arm_neon_vminnm:
3997 case Intrinsic::arm_neon_vmaxnm: {
3998 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3999 ? ISD::FMINNUM : ISD::FMAXNUM;
4000 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4001 Op.getOperand(1), Op.getOperand(2));
4002 }
4003 case Intrinsic::arm_neon_vminu:
4004 case Intrinsic::arm_neon_vmaxu: {
4005 if (Op.getValueType().isFloatingPoint())
4006 return SDValue();
4007 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
4008 ? ISD::UMIN : ISD::UMAX;
4009 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4010 Op.getOperand(1), Op.getOperand(2));
4011 }
4012 case Intrinsic::arm_neon_vmins:
4013 case Intrinsic::arm_neon_vmaxs: {
4014 // v{min,max}s is overloaded between signed integers and floats.
4015 if (!Op.getValueType().isFloatingPoint()) {
4016 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
4017 ? ISD::SMIN : ISD::SMAX;
4018 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4019 Op.getOperand(1), Op.getOperand(2));
4020 }
4021 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
4022 ? ISD::FMINIMUM : ISD::FMAXIMUM;
4023 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4024 Op.getOperand(1), Op.getOperand(2));
4025 }
4026 case Intrinsic::arm_neon_vtbl1:
4027 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
4028 Op.getOperand(1), Op.getOperand(2));
4029 case Intrinsic::arm_neon_vtbl2:
4030 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
4031 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4032 case Intrinsic::arm_mve_pred_i2v:
4033 case Intrinsic::arm_mve_pred_v2i:
4034 return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(),
4035 Op.getOperand(1));
4036 case Intrinsic::arm_mve_vreinterpretq:
4037 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(Op), Op.getValueType(),
4038 Op.getOperand(1));
4039 case Intrinsic::arm_mve_lsll:
4040 return DAG.getNode(ARMISD::LSLL, SDLoc(Op), Op->getVTList(),
4041 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4042 case Intrinsic::arm_mve_asrl:
4043 return DAG.getNode(ARMISD::ASRL, SDLoc(Op), Op->getVTList(),
4044 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4045 case Intrinsic::arm_mve_vsli:
4046 return DAG.getNode(ARMISD::VSLIIMM, SDLoc(Op), Op->getVTList(),
4047 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4048 case Intrinsic::arm_mve_vsri:
4049 return DAG.getNode(ARMISD::VSRIIMM, SDLoc(Op), Op->getVTList(),
4050 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4051 }
4052}
4053
4055 const ARMSubtarget *Subtarget) {
4056 SDLoc dl(Op);
4057 auto SSID = static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
4058 if (SSID == SyncScope::SingleThread)
4059 return Op;
4060
4061 if (!Subtarget->hasDataBarrier()) {
4062 // Some ARMv6 cpus can support data barriers with an mcr instruction.
4063 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
4064 // here.
4065 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
4066 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
4067 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
4068 DAG.getConstant(0, dl, MVT::i32));
4069 }
4070
4071 AtomicOrdering Ord =
4072 static_cast<AtomicOrdering>(Op.getConstantOperandVal(1));
4074 if (Subtarget->isMClass()) {
4075 // Only a full system barrier exists in the M-class architectures.
4077 } else if (Subtarget->preferISHSTBarriers() &&
4078 Ord == AtomicOrdering::Release) {
4079 // Swift happens to implement ISHST barriers in a way that's compatible with
4080 // Release semantics but weaker than ISH so we'd be fools not to use
4081 // it. Beware: other processors probably don't!
4083 }
4084
4085 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
4086 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
4087 DAG.getConstant(Domain, dl, MVT::i32));
4088}
4089
4091 const ARMSubtarget *Subtarget) {
4092 // ARM pre v5TE and Thumb1 does not have preload instructions.
4093 if (!(Subtarget->isThumb2() ||
4094 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
4095 // Just preserve the chain.
4096 return Op.getOperand(0);
4097
4098 SDLoc dl(Op);
4099 unsigned isRead = ~Op.getConstantOperandVal(2) & 1;
4100 if (!isRead &&
4101 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
4102 // ARMv7 with MP extension has PLDW.
4103 return Op.getOperand(0);
4104
4105 unsigned isData = Op.getConstantOperandVal(4);
4106 if (Subtarget->isThumb()) {
4107 // Invert the bits.
4108 isRead = ~isRead & 1;
4109 isData = ~isData & 1;
4110 }
4111
4112 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
4113 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
4114 DAG.getConstant(isData, dl, MVT::i32));
4115}
4116
4119 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
4120
4121 // vastart just stores the address of the VarArgsFrameIndex slot into the
4122 // memory location argument.
4123 SDLoc dl(Op);
4125 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4126 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4127 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
4128 MachinePointerInfo(SV));
4129}
4130
4131SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
4132 CCValAssign &NextVA,
4133 SDValue &Root,
4134 SelectionDAG &DAG,
4135 const SDLoc &dl) const {
4137 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4138
4139 const TargetRegisterClass *RC;
4140 if (AFI->isThumb1OnlyFunction())
4141 RC = &ARM::tGPRRegClass;
4142 else
4143 RC = &ARM::GPRRegClass;
4144
4145 // Transform the arguments stored in physical registers into virtual ones.
4146 Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4147 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4148
4149 SDValue ArgValue2;
4150 if (NextVA.isMemLoc()) {
4151 MachineFrameInfo &MFI = MF.getFrameInfo();
4152 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
4153
4154 // Create load node to retrieve arguments from the stack.
4155 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4156 ArgValue2 = DAG.getLoad(
4157 MVT::i32, dl, Root, FIN,
4159 } else {
4160 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
4161 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4162 }
4163 if (!Subtarget->isLittle())
4164 std::swap (ArgValue, ArgValue2);
4165 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
4166}
4167
4168// The remaining GPRs hold either the beginning of variable-argument
4169// data, or the beginning of an aggregate passed by value (usually
4170// byval). Either way, we allocate stack slots adjacent to the data
4171// provided by our caller, and store the unallocated registers there.
4172// If this is a variadic function, the va_list pointer will begin with
4173// these values; otherwise, this reassembles a (byval) structure that
4174// was split between registers and memory.
4175// Return: The frame index registers were stored into.
4176int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
4177 const SDLoc &dl, SDValue &Chain,
4178 const Value *OrigArg,
4179 unsigned InRegsParamRecordIdx,
4180 int ArgOffset, unsigned ArgSize) const {
4181 // Currently, two use-cases possible:
4182 // Case #1. Non-var-args function, and we meet first byval parameter.
4183 // Setup first unallocated register as first byval register;
4184 // eat all remained registers
4185 // (these two actions are performed by HandleByVal method).
4186 // Then, here, we initialize stack frame with
4187 // "store-reg" instructions.
4188 // Case #2. Var-args function, that doesn't contain byval parameters.
4189 // The same: eat all remained unallocated registers,
4190 // initialize stack frame.
4191
4193 MachineFrameInfo &MFI = MF.getFrameInfo();
4194 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4195 unsigned RBegin, REnd;
4196 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
4197 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
4198 } else {
4199 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4200 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
4201 REnd = ARM::R4;
4202 }
4203
4204 if (REnd != RBegin)
4205 ArgOffset = -4 * (ARM::R4 - RBegin);
4206
4207 auto PtrVT = getPointerTy(DAG.getDataLayout());
4208 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
4209 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
4210
4212 const TargetRegisterClass *RC =
4213 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
4214
4215 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
4216 Register VReg = MF.addLiveIn(Reg, RC);
4217 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4218 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4219 MachinePointerInfo(OrigArg, 4 * i));
4220 MemOps.push_back(Store);
4221 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
4222 }
4223
4224 if (!MemOps.empty())
4225 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4226 return FrameIndex;
4227}
4228
4229// Setup stack frame, the va_list pointer will start from.
4230void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
4231 const SDLoc &dl, SDValue &Chain,
4232 unsigned ArgOffset,
4233 unsigned TotalArgRegsSaveSize,
4234 bool ForceMutable) const {
4236 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4237
4238 // Try to store any remaining integer argument regs
4239 // to their spots on the stack so that they may be loaded by dereferencing
4240 // the result of va_next.
4241 // If there is no regs to be stored, just point address after last
4242 // argument passed via stack.
4243 int FrameIndex = StoreByValRegs(
4244 CCInfo, DAG, dl, Chain, nullptr, CCInfo.getInRegsParamsCount(),
4245 CCInfo.getStackSize(), std::max(4U, TotalArgRegsSaveSize));
4246 AFI->setVarArgsFrameIndex(FrameIndex);
4247}
4248
4249bool ARMTargetLowering::splitValueIntoRegisterParts(
4250 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
4251 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
4252 EVT ValueVT = Val.getValueType();
4253 if ((ValueVT == MVT::f16 || ValueVT == MVT::bf16) && PartVT == MVT::f32) {
4254 unsigned ValueBits = ValueVT.getSizeInBits();
4255 unsigned PartBits = PartVT.getSizeInBits();
4256 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(ValueBits), Val);
4257 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::getIntegerVT(PartBits), Val);
4258 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
4259 Parts[0] = Val;
4260 return true;
4261 }
4262 return false;
4263}
4264
4265SDValue ARMTargetLowering::joinRegisterPartsIntoValue(
4266 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
4267 MVT PartVT, EVT ValueVT, std::optional<CallingConv::ID> CC) const {
4268 if ((ValueVT == MVT::f16 || ValueVT == MVT::bf16) && PartVT == MVT::f32) {
4269 unsigned ValueBits = ValueVT.getSizeInBits();
4270 unsigned PartBits = PartVT.getSizeInBits();
4271 SDValue Val = Parts[0];
4272
4273 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(PartBits), Val);
4274 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::getIntegerVT(ValueBits), Val);
4275 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
4276 return Val;
4277 }
4278 return SDValue();
4279}
4280
4281SDValue ARMTargetLowering::LowerFormalArguments(
4282 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4283 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4284 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4286 MachineFrameInfo &MFI = MF.getFrameInfo();
4287
4288 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4289
4290 // Assign locations to all of the incoming arguments.
4292 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4293 *DAG.getContext());
4294 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
4295
4297 unsigned CurArgIdx = 0;
4298
4299 // Initially ArgRegsSaveSize is zero.
4300 // Then we increase this value each time we meet byval parameter.
4301 // We also increase this value in case of varargs function.
4302 AFI->setArgRegsSaveSize(0);
4303
4304 // Calculate the amount of stack space that we need to allocate to store
4305 // byval and variadic arguments that are passed in registers.
4306 // We need to know this before we allocate the first byval or variadic
4307 // argument, as they will be allocated a stack slot below the CFA (Canonical
4308 // Frame Address, the stack pointer at entry to the function).
4309 unsigned ArgRegBegin = ARM::R4;
4310 for (const CCValAssign &VA : ArgLocs) {
4311 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
4312 break;
4313
4314 unsigned Index = VA.getValNo();
4315 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
4316 if (!Flags.isByVal())
4317 continue;
4318
4319 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
4320 unsigned RBegin, REnd;
4321 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
4322 ArgRegBegin = std::min(ArgRegBegin, RBegin);
4323
4324 CCInfo.nextInRegsParam();
4325 }
4326 CCInfo.rewindByValRegsInfo();
4327
4328 int lastInsIndex = -1;
4329 if (isVarArg && MFI.hasVAStart()) {
4330 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4331 if (RegIdx != std::size(GPRArgRegs))
4332 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
4333 }
4334
4335 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
4336 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
4337 auto PtrVT = getPointerTy(DAG.getDataLayout());
4338
4339 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4340 CCValAssign &VA = ArgLocs[i];
4341 if (Ins[VA.getValNo()].isOrigArg()) {
4342 std::advance(CurOrigArg,
4343 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
4344 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
4345 }
4346 // Arguments stored in registers.
4347 if (VA.isRegLoc()) {
4348 EVT RegVT = VA.getLocVT();
4349 SDValue ArgValue;
4350
4351 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
4352 // f64 and vector types are split up into multiple registers or
4353 // combinations of registers and stack slots.
4354 SDValue ArgValue1 =
4355 GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4356 VA = ArgLocs[++i]; // skip ahead to next loc
4357 SDValue ArgValue2;
4358 if (VA.isMemLoc()) {
4359 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
4360 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4361 ArgValue2 = DAG.getLoad(
4362 MVT::f64, dl, Chain, FIN,
4364 } else {
4365 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4366 }
4367 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
4368 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4369 ArgValue1, DAG.getIntPtrConstant(0, dl));
4370 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4371 ArgValue2, DAG.getIntPtrConstant(1, dl));
4372 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
4373 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4374 } else {
4375 const TargetRegisterClass *RC;
4376
4377 if (RegVT == MVT::f16 || RegVT == MVT::bf16)
4378 RC = &ARM::HPRRegClass;
4379 else if (RegVT == MVT::f32)
4380 RC = &ARM::SPRRegClass;
4381 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16 ||
4382 RegVT == MVT::v4bf16)
4383 RC = &ARM::DPRRegClass;
4384 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16 ||
4385 RegVT == MVT::v8bf16)
4386 RC = &ARM::QPRRegClass;
4387 else if (RegVT == MVT::i32)
4388 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
4389 : &ARM::GPRRegClass;
4390 else
4391 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
4392
4393 // Transform the arguments in physical registers into virtual ones.
4394 Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4395 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
4396
4397 // If this value is passed in r0 and has the returned attribute (e.g.
4398 // C++ 'structors), record this fact for later use.
4399 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4400 AFI->setPreservesR0();
4401 }
4402 }
4403
4404 // If this is an 8 or 16-bit value, it is really passed promoted
4405 // to 32 bits. Insert an assert[sz]ext to capture this, then
4406 // truncate to the right size.
4407 switch (VA.getLocInfo()) {
4408 default: llvm_unreachable("Unknown loc info!");
4409 case CCValAssign::Full: break;
4410 case CCValAssign::BCvt:
4411 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4412 break;
4413 }
4414
4415 // f16 arguments have their size extended to 4 bytes and passed as if they
4416 // had been copied to the LSBs of a 32-bit register.
4417 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
4418 if (VA.needsCustom() &&
4419 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
4420 ArgValue = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), ArgValue);
4421
4422 // On CMSE Entry Functions, formal integer arguments whose bitwidth is
4423 // less than 32 bits must be sign- or zero-extended in the callee for
4424 // security reasons. Although the ABI mandates an extension done by the
4425 // caller, the latter cannot be trusted to follow the rules of the ABI.
4426 const ISD::InputArg &Arg = Ins[VA.getValNo()];
4427 if (AFI->isCmseNSEntryFunction() && Arg.ArgVT.isScalarInteger() &&
4428 RegVT.isScalarInteger() && Arg.ArgVT.bitsLT(MVT::i32))
4429 ArgValue = handleCMSEValue(ArgValue, Arg, DAG, dl);
4430
4431 InVals.push_back(ArgValue);
4432 } else { // VA.isRegLoc()
4433 // Only arguments passed on the stack should make it here.
4434 assert(VA.isMemLoc());
4435 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4436
4437 int index = VA.getValNo();
4438
4439 // Some Ins[] entries become multiple ArgLoc[] entries.
4440 // Process them only once.
4441 if (index != lastInsIndex)
4442 {
4443 ISD::ArgFlagsTy Flags = Ins[index].Flags;
4444 // FIXME: For now, all byval parameter objects are marked mutable.
4445 // This can be changed with more analysis.
4446 // In case of tail call optimization mark all arguments mutable.
4447 // Since they could be overwritten by lowering of arguments in case of
4448 // a tail call.
4449 if (Flags.isByVal()) {
4450 assert(Ins[index].isOrigArg() &&
4451 "Byval arguments cannot be implicit");
4452 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4453
4454 int FrameIndex = StoreByValRegs(
4455 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4456 VA.getLocMemOffset(), Flags.getByValSize());
4457 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4458 CCInfo.nextInRegsParam();
4459 } else if (VA.needsCustom() && (VA.getValVT() == MVT::f16 ||
4460 VA.getValVT() == MVT::bf16)) {
4461 // f16 and bf16 values are passed in the least-significant half of
4462 // a 4 byte stack slot. This is done as-if the extension was done
4463 // in a 32-bit register, so the actual bytes used for the value
4464 // differ between little and big endian.
4465 assert(VA.getLocVT().getSizeInBits() == 32);
4466 unsigned FIOffset = VA.getLocMemOffset();
4467 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits() / 8,
4468 FIOffset, true);
4469
4470 SDValue Addr = DAG.getFrameIndex(FI, PtrVT);
4471 if (DAG.getDataLayout().isBigEndian())
4472 Addr = DAG.getObjectPtrOffset(dl, Addr, TypeSize::getFixed(2));
4473
4474 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, Addr,
4476 DAG.getMachineFunction(), FI)));
4477
4478 } else {
4479 unsigned FIOffset = VA.getLocMemOffset();
4480 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4481 FIOffset, true);
4482
4483 // Create load nodes to retrieve arguments from the stack.
4484 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4485 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4487 DAG.getMachineFunction(), FI)));
4488 }
4489 lastInsIndex = index;
4490 }
4491 }
4492 }
4493
4494 // varargs
4495 if (isVarArg && MFI.hasVAStart()) {
4496 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getStackSize(),
4497 TotalArgRegsSaveSize);
4498 if (AFI->isCmseNSEntryFunction()) {
4499 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
4501 "secure entry function must not be variadic", dl.getDebugLoc()));
4502 }
4503 }
4504
4505 // A variadic function that forwards through a musttail call needs its unnamed
4506 // register arguments modelled as live, so the allocator does not use one as
4507 // scratch. This must run after the va_list save area above, which consumes
4508 // the same registers, and is deliberately *not* predicated on hasVAStart():
4509 // a forwarding thunk never calls va_start.
4510 if (isVarArg && MFI.hasMustTailInVarArgFunc()) {
4511 // getRemainingRegParmsForType() walks the assign function until an argument
4512 // lands in memory, so the convention must have a stack fallback. GHC and
4513 // the Windows CFGuard check stub assign to registers only and would run off
4514 // the end of their tables; neither supports variadic arguments anyway.
4515 CallingConv::ID EffCC = getEffectiveCallingConv(CallConv, isVarArg);
4516 if (EffCC != CallingConv::GHC && EffCC != CallingConv::CFGuard_Check) {
4517 // Only the core registers can hold an unnamed argument:
4518 // getEffectiveCallingConv() degrades every VFP convention to ARM_AAPCS
4519 // when isVarArg is set.
4520 SmallVector<MVT, 1> RegParmTypes;
4521 RegParmTypes.push_back(MVT::i32);
4522 SmallVectorImpl<ForwardedRegister> &Forwards =
4525 Forwards, RegParmTypes, CCAssignFnForCall(CallConv, isVarArg));
4526 }
4527 }
4528
4529 unsigned StackArgSize = CCInfo.getStackSize();
4530 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4531 if (canGuaranteeTCO(CallConv, TailCallOpt)) {
4532 // The only way to guarantee a tail call is if the callee restores its
4533 // argument area, but it must also keep the stack aligned when doing so.
4534 MaybeAlign StackAlign = DAG.getDataLayout().getStackAlignment();
4535 assert(StackAlign && "data layout string is missing stack alignment");
4536 StackArgSize = alignTo(StackArgSize, *StackAlign);
4537
4538 AFI->setArgumentStackToRestore(StackArgSize);
4539 }
4540 AFI->setArgumentStackSize(StackArgSize);
4541
4542 if (CCInfo.getStackSize() > 0 && AFI->isCmseNSEntryFunction()) {
4543 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
4545 "secure entry function requires arguments on stack", dl.getDebugLoc()));
4546 }
4547
4548 return Chain;
4549}
4550
4551/// isFloatingPointZero - Return true if this is +0.0.
4554 return CFP->getValueAPF().isPosZero();
4555 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4556 // Maybe this has already been legalized into the constant pool?
4557 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4558 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4560 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4561 return CFP->getValueAPF().isPosZero();
4562 }
4563 } else if (Op->getOpcode() == ISD::BITCAST &&
4564 Op->getValueType(0) == MVT::f64) {
4565 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4566 // created by LowerConstantFP().
4567 SDValue BitcastOp = Op->getOperand(0);
4568 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4569 isNullConstant(BitcastOp->getOperand(0)))
4570 return true;
4571 }
4572 return false;
4573}
4574
4576 // 0 - INT_MIN sign wraps, so no signed wrap means cmn is safe.
4577 if (Op->getFlags().hasNoSignedWrap())
4578 return true;
4579
4580 // We can still figure out if the second operand is safe to use
4581 // in a CMN instruction by checking if it is known to be not the minimum
4582 // signed value. If it is not, then we can safely use CMN.
4583 // Note: We can eventually remove this check and simply rely on
4584 // Op->getFlags().hasNoSignedWrap() once SelectionDAG/ISelLowering
4585 // consistently sets them appropriately when making said nodes.
4586
4587 KnownBits KnownSrc = DAG.computeKnownBits(Op.getOperand(1));
4588 return !KnownSrc.getSignedMinValue().isMinSignedValue();
4589}
4590
4592 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
4593 (isIntEqualitySetCC(CC) ||
4594 (isUnsignedIntSetCC(CC) && DAG.isKnownNeverZero(Op.getOperand(1))) ||
4595 (isSignedIntSetCC(CC) && isSafeSignedCMN(Op, DAG)));
4596}
4597
4598/// Returns how profitable it is to fold a comparison's operand's shift and/or
4599/// extension operations into the comparison instruction's second operand
4600/// (so_reg_imm / so_reg_reg for ARM, t2_so_reg for Thumb-2).
4602 // Thumb-1 CMP does not support shifted second operands.
4603 if (ST.isThumb1Only() || !Op.hasOneUse())
4604 return 0;
4605
4606 unsigned Opc = Op.getOpcode();
4607 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA) {
4608 if (auto *ShiftAmt = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
4609 return ShiftAmt->getZExtValue() <= 31 ? 1 : 0;
4610 // Register-controlled shift: only ARM-mode CMP/CMN (so_reg_reg) supports
4611 // this; Thumb-2 t2_so_reg requires an immediate shift amount.
4612 return ST.isThumb() ? 0 : 1;
4613 }
4614
4615 if (Opc == ISD::ROTR) {
4616 // Rotr constants will be normalized via mod 32, or & 31,
4617 // so we do not have to bounds check.
4618 if (isa<ConstantSDNode>(Op.getOperand(1)))
4619 return 1;
4620 return ST.isThumb() ? 0 : 1;
4621 }
4622
4623 return 0;
4624}
4625
4626// Return a cheaper value with the same zero/nonzero result as a low-mask AND.
4628 const SDLoc &DL) {
4629 if (Value.getValueType() != MVT::i32 || Value.getOpcode() != ISD::AND ||
4630 !Value.hasOneUse())
4631 return SDValue();
4632
4633 auto *Mask = dyn_cast<ConstantSDNode>(Value.getOperand(1));
4634 if (!Mask)
4635 return SDValue();
4636 uint32_t MaskValue = Mask->getZExtValue();
4637 // Keep the existing single-bit lowering and UXTB/UXTH for byte/halfword
4638 // masks, and avoid a zero or no-op shift.
4639 if (!isMask_32(MaskValue) || MaskValue == 1 || MaskValue == 0xff ||
4640 MaskValue == 0xffff || MaskValue == ~0U)
4641 return SDValue();
4642
4643 return DAG.getNode(
4644 ISD::SHL, DL, MVT::i32, Value.getOperand(0),
4645 DAG.getConstant(llvm::countl_zero(MaskValue), DL, MVT::i32));
4646}
4647
4648/// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4649/// the given operands.
4650SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4651 SDValue &ARMcc, SelectionDAG &DAG,
4652 const SDLoc &dl) const {
4653 // For a zero test, replace a low-mask AND feeding an OR with a shift. ARM
4654 // and Thumb-2 can fold the shift into the OR. Require single uses to avoid
4655 // duplicating live work.
4656 if (!Subtarget->isThumb1Only() && isIntEqualitySetCC(CC) &&
4657 isNullConstant(RHS) && LHS.getValueType() == MVT::i32 &&
4658 LHS.getOpcode() == ISD::OR && LHS.hasOneUse()) {
4659 for (unsigned I = 0; I != 2; ++I) {
4660 if (SDValue Shift =
4661 getShiftedLowMaskZeroTest(LHS.getOperand(I), DAG, dl)) {
4662 LHS = DAG.getNode(ISD::OR, dl, MVT::i32, LHS.getOperand(I ^ 1), Shift);
4663 break;
4664 }
4665 }
4666 }
4667
4668 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4669 unsigned C = RHSC->getZExtValue();
4670 if (!isLegalICmpImmediate((int32_t)C)) {
4671 // Constant does not fit, try adjusting it by one.
4672 switch (CC) {
4673 default: break;
4674 case ISD::SETLT:
4675 case ISD::SETGE:
4676 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4677 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4678 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4679 }
4680 break;
4681 case ISD::SETULT:
4682 case ISD::SETUGE:
4683 if (C != 0 && isLegalICmpImmediate(C-1)) {
4684 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4685 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4686 }
4687 break;
4688 case ISD::SETLE:
4689 case ISD::SETGT:
4690 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4691 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4692 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4693 }
4694 break;
4695 case ISD::SETULE:
4696 case ISD::SETUGT:
4697 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4698 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4699 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4700 }
4701 break;
4702 }
4703 }
4704 }
4705
4706 // Thumb1 has very limited immediate modes, so turning an "and" into a
4707 // shift can save multiple instructions.
4708 //
4709 // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4710 // into "((x << n) >> n)". But that isn't necessarily profitable on its
4711 // own. If it's the operand to an unsigned comparison with an immediate,
4712 // we can eliminate one of the shifts: we transform
4713 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4714 //
4715 // We avoid transforming cases which aren't profitable due to encoding
4716 // details:
4717 //
4718 // 1. C2 fits into the immediate field of a cmp, and the transformed version
4719 // would not; in that case, we're essentially trading one immediate load for
4720 // another.
4721 // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4722 // 3. C2 is zero; we have other code for this special case.
4723 //
4724 // FIXME: Figure out profitability for Thumb2; we usually can't save an
4725 // instruction, since the AND is always one instruction anyway, but we could
4726 // use narrow instructions in some cases.
4727 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4728 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4729 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4730 !isSignedIntSetCC(CC)) {
4731 unsigned Mask = LHS.getConstantOperandVal(1);
4732 auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4733 uint64_t RHSV = RHSC->getZExtValue();
4734 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4735 unsigned ShiftBits = llvm::countl_zero(Mask);
4736 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4737 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4738 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4739 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4740 }
4741 }
4742 }
4743
4744 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4745 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same
4746 // way a cmp would.
4747 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4748 // some tweaks to the heuristics for the previous and->shift transform.
4749 // FIXME: Optimize cases where the LHS isn't a shift.
4750 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4751 isa<ConstantSDNode>(RHS) && RHS->getAsZExtVal() == 0x80000000U &&
4752 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4753 LHS.getConstantOperandVal(1) < 31) {
4754 unsigned ShiftAmt = LHS.getConstantOperandVal(1) + 1;
4755 SDValue Shift =
4756 DAG.getNode(ARMISD::LSLS, dl, DAG.getVTList(MVT::i32, FlagsVT),
4757 LHS.getOperand(0), DAG.getConstant(ShiftAmt, dl, MVT::i32));
4758 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4759 return Shift.getValue(1);
4760 }
4761
4763
4764 unsigned CompareType;
4765 switch (CondCode) {
4766 default:
4767 CompareType = ARMISD::CMP;
4768 break;
4769 case ARMCC::EQ:
4770 case ARMCC::NE:
4771 // Uses only Z Flag
4772 CompareType = ARMISD::CMPZ;
4773 break;
4774 }
4775
4776 // TODO: Remove CMPZ check once we generalize and remove the CMPZ enum from
4777 // the codebase.
4778
4779 // TODO: When we have a solution to the vselect predicate not allowing pl/mi
4780 // all the time, allow those cases to be cmn too no matter what.
4781 if (CompareType != ARMISD::CMPZ && isCMN(RHS, CC, DAG)) {
4782 CompareType = ARMISD::CMN;
4783 RHS = RHS.getOperand(1);
4784 } else if (CompareType != ARMISD::CMPZ && isCMN(LHS, CC, DAG)) {
4785 CompareType = ARMISD::CMN;
4786 LHS = LHS.getOperand(1);
4788 }
4789
4790 // Prefer folding shifts / CMN into the cmp/cmn second operand (so_reg /
4791 // t2_so_reg). When both sides compete, pick the higher
4792 // getCmpOperandFoldingProfit. Only when RHS is not a legal icmp
4793 // immediate: otherwise keep the canonical (reg, imm) form.
4794 ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getNode());
4795 if (!C || !isLegalICmpImmediate(C->getSExtValue())) {
4796 if (getCmpOperandFoldingProfit(LHS, *Subtarget) >
4797 getCmpOperandFoldingProfit(RHS, *Subtarget)) {
4798 std::swap(LHS, RHS);
4799 if (CompareType == ARMISD::CMP)
4801 }
4802 }
4803
4804 // If the RHS is a constant zero then the V (overflow) flag will never be
4805 // set. This can allow us to simplify GE to PL or LT to MI, which can be
4806 // simpler for other passes (like the peephole optimiser) to deal with.
4807 if (isNullConstant(RHS)) {
4808 switch (CondCode) {
4809 default:
4810 break;
4811 case ARMCC::GE:
4813 break;
4814 case ARMCC::LT:
4816 break;
4817 }
4818 }
4819
4820 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4821 return DAG.getNode(CompareType, dl, FlagsVT, LHS, RHS);
4822}
4823
4824/// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4825SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4826 SelectionDAG &DAG, const SDLoc &dl,
4827 bool Signaling) const {
4828 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4829 SDValue Flags;
4831 Flags = DAG.getNode(Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP, dl, FlagsVT,
4832 LHS, RHS);
4833 else
4834 Flags = DAG.getNode(Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0, dl,
4835 FlagsVT, LHS);
4836 return DAG.getNode(ARMISD::FMSTAT, dl, FlagsVT, Flags);
4837}
4838
4839// This function returns three things: the arithmetic computation itself
4840// (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The
4841// comparison and the condition code define the case in which the arithmetic
4842// computation *does not* overflow.
4843std::pair<SDValue, SDValue>
4844ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4845 SDValue &ARMcc) const {
4846 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
4847
4848 SDValue Value, OverflowCmp;
4849 SDValue LHS = Op.getOperand(0);
4850 SDValue RHS = Op.getOperand(1);
4851 SDLoc dl(Op);
4852
4853 // FIXME: We are currently always generating CMPs because we don't support
4854 // generating CMN through the backend. This is not as good as the natural
4855 // CMP case because it causes a register dependency and cannot be folded
4856 // later.
4857
4858 switch (Op.getOpcode()) {
4859 default:
4860 llvm_unreachable("Unknown overflow instruction!");
4861 case ISD::SADDO:
4862 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4863 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4864 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, FlagsVT, Value, LHS);
4865 break;
4866 case ISD::UADDO:
4867 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4868 // We use ADDC here to correspond to its use in LowerALUO.
4869 // We do not use it in the USUBO case as Value may not be used.
4870 Value = DAG.getNode(ARMISD::ADDC, dl,
4871 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4872 .getValue(0);
4873 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, FlagsVT, Value, LHS);
4874 break;
4875 case ISD::SSUBO:
4876 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4877 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4878 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, FlagsVT, LHS, RHS);
4879 break;
4880 case ISD::USUBO:
4881 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4882 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4883 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, FlagsVT, LHS, RHS);
4884 break;
4885 case ISD::UMULO:
4886 // We generate a UMUL_LOHI and then check if the high word is 0.
4887 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4888 Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4889 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4890 LHS, RHS);
4891 OverflowCmp = DAG.getNode(ARMISD::CMPZ, dl, FlagsVT, Value.getValue(1),
4892 DAG.getConstant(0, dl, MVT::i32));
4893 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4894 break;
4895 case ISD::SMULO:
4896 // We generate a SMUL_LOHI and then check if all the bits of the high word
4897 // are the same as the sign bit of the low word.
4898 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4899 Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4900 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4901 LHS, RHS);
4902 OverflowCmp = DAG.getNode(ARMISD::CMPZ, dl, FlagsVT, Value.getValue(1),
4903 DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4904 Value.getValue(0),
4905 DAG.getConstant(31, dl, MVT::i32)));
4906 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4907 break;
4908 } // switch (...)
4909
4910 return std::make_pair(Value, OverflowCmp);
4911}
4912
4914 SDLoc DL(Value);
4915 EVT VT = Value.getValueType();
4916
4917 if (Invert)
4918 Value = DAG.getNode(ISD::SUB, DL, MVT::i32,
4919 DAG.getConstant(1, DL, MVT::i32), Value);
4920
4921 SDValue Cmp = DAG.getNode(ARMISD::SUBC, DL, DAG.getVTList(VT, MVT::i32),
4922 Value, DAG.getConstant(1, DL, VT));
4923 return Cmp.getValue(1);
4924}
4925
4927 bool Invert) {
4928 SDLoc DL(Flags);
4929
4930 if (Invert) {
4931 // Convert flags to boolean with ADDE 0,0,Carry then compute 1 - bool.
4932 SDValue BoolCarry = DAG.getNode(
4933 ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4934 DAG.getConstant(0, DL, VT), DAG.getConstant(0, DL, VT), Flags);
4935 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(1, DL, VT), BoolCarry);
4936 }
4937
4938 // Now convert the carry flag into a boolean carry. We do this
4939 // using ARMISD::ADDE 0, 0, Carry
4940 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4941 DAG.getConstant(0, DL, VT), DAG.getConstant(0, DL, VT),
4942 Flags);
4943}
4944
4945// Value is 1 if 'V' bit is 1, else 0
4947 SDLoc DL(Flags);
4948 SDValue Zero = DAG.getConstant(0, DL, VT);
4949 SDValue One = DAG.getConstant(1, DL, VT);
4950 SDValue ARMcc = DAG.getConstant(ARMCC::VS, DL, MVT::i32);
4951 return DAG.getNode(ARMISD::CMOV, DL, VT, Zero, One, ARMcc, Flags);
4952}
4953
4954SDValue ARMTargetLowering::LowerALUO(SDValue Op, SelectionDAG &DAG) const {
4955 // Let legalize expand this if it isn't a legal type yet.
4956 if (!isTypeLegal(Op.getValueType()))
4957 return SDValue();
4958
4959 SDValue LHS = Op.getOperand(0);
4960 SDValue RHS = Op.getOperand(1);
4961 SDLoc dl(Op);
4962
4963 EVT VT = Op.getValueType();
4964 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4965 SDValue Value;
4966 SDValue Overflow;
4967 switch (Op.getOpcode()) {
4968 case ISD::UADDO:
4969 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4970 // Convert the carry flag into a boolean value.
4971 Overflow = carryFlagToValue(Value.getValue(1), VT, DAG, false);
4972 break;
4973 case ISD::USUBO:
4974 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4975 // Convert the carry flag into a boolean value.
4976 Overflow = carryFlagToValue(Value.getValue(1), VT, DAG, true);
4977 break;
4978 default: {
4979 // Handle other operations with getARMXALUOOp
4980 SDValue OverflowCmp, ARMcc;
4981 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4982 // We use 0 and 1 as false and true values.
4983 // ARMcc represents the "no overflow" condition (e.g., VC for signed ops).
4984 // CMOV operand order is (FalseVal, TrueVal), so we put 1 in FalseVal
4985 // position to get Overflow=1 when the "no overflow" condition is false.
4986 Overflow =
4987 DAG.getNode(ARMISD::CMOV, dl, MVT::i32,
4988 DAG.getConstant(1, dl, MVT::i32), // FalseVal: overflow
4989 DAG.getConstant(0, dl, MVT::i32), // TrueVal: no overflow
4990 ARMcc, OverflowCmp);
4991 break;
4992 }
4993 }
4994
4995 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4996}
4997
4999 const ARMSubtarget *Subtarget) {
5000 EVT VT = Op.getValueType();
5001 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP() || Subtarget->isThumb1Only())
5002 return SDValue();
5003 if (!VT.isSimple())
5004 return SDValue();
5005
5006 unsigned NewOpcode;
5007 switch (VT.getSimpleVT().SimpleTy) {
5008 default:
5009 return SDValue();
5010 case MVT::i8:
5011 switch (Op->getOpcode()) {
5012 case ISD::UADDSAT:
5013 NewOpcode = ARMISD::UQADD8b;
5014 break;
5015 case ISD::SADDSAT:
5016 NewOpcode = ARMISD::QADD8b;
5017 break;
5018 case ISD::USUBSAT:
5019 NewOpcode = ARMISD::UQSUB8b;
5020 break;
5021 case ISD::SSUBSAT:
5022 NewOpcode = ARMISD::QSUB8b;
5023 break;
5024 }
5025 break;
5026 case MVT::i16:
5027 switch (Op->getOpcode()) {
5028 case ISD::UADDSAT:
5029 NewOpcode = ARMISD::UQADD16b;
5030 break;
5031 case ISD::SADDSAT:
5032 NewOpcode = ARMISD::QADD16b;
5033 break;
5034 case ISD::USUBSAT:
5035 NewOpcode = ARMISD::UQSUB16b;
5036 break;
5037 case ISD::SSUBSAT:
5038 NewOpcode = ARMISD::QSUB16b;
5039 break;
5040 }
5041 break;
5042 }
5043
5044 SDLoc dl(Op);
5045 SDValue Add =
5046 DAG.getNode(NewOpcode, dl, MVT::i32,
5047 DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32),
5048 DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32));
5049 return DAG.getNode(ISD::TRUNCATE, dl, VT, Add);
5050}
5051
5052SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
5053 SDValue Cond = Op.getOperand(0);
5054 SDValue SelectTrue = Op.getOperand(1);
5055 SDValue SelectFalse = Op.getOperand(2);
5056 SDLoc dl(Op);
5057 unsigned Opc = Cond.getOpcode();
5058
5059 if (Cond.getResNo() == 1 &&
5060 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5061 Opc == ISD::USUBO)) {
5062 if (!isTypeLegal(Cond->getValueType(0)))
5063 return SDValue();
5064
5065 SDValue Value, OverflowCmp;
5066 SDValue ARMcc;
5067 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5068 EVT VT = Op.getValueType();
5069
5070 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, OverflowCmp, DAG);
5071 }
5072
5073 // Convert:
5074 //
5075 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
5076 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
5077 //
5078 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
5079 const ConstantSDNode *CMOVTrue =
5080 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
5081 const ConstantSDNode *CMOVFalse =
5082 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
5083
5084 if (CMOVTrue && CMOVFalse) {
5085 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
5086 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
5087
5088 SDValue True;
5089 SDValue False;
5090 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
5091 True = SelectTrue;
5092 False = SelectFalse;
5093 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
5094 True = SelectFalse;
5095 False = SelectTrue;
5096 }
5097
5098 if (True.getNode() && False.getNode())
5099 return getCMOV(dl, Op.getValueType(), True, False, Cond.getOperand(2),
5100 Cond.getOperand(3), DAG);
5101 }
5102 }
5103
5104 return DAG.getSelectCC(dl, Cond,
5105 DAG.getConstant(0, dl, Cond.getValueType()),
5106 SelectTrue, SelectFalse, ISD::SETNE);
5107}
5108
5110 bool &swpCmpOps, bool &swpVselOps) {
5111 // Start by selecting the GE condition code for opcodes that return true for
5112 // 'equality'
5113 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
5114 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE)
5115 CondCode = ARMCC::GE;
5116
5117 // and GT for opcodes that return false for 'equality'.
5118 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
5119 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT)
5120 CondCode = ARMCC::GT;
5121
5122 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
5123 // to swap the compare operands.
5124 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
5125 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT)
5126 swpCmpOps = true;
5127
5128 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
5129 // If we have an unordered opcode, we need to swap the operands to the VSEL
5130 // instruction (effectively negating the condition).
5131 //
5132 // This also has the effect of swapping which one of 'less' or 'greater'
5133 // returns true, so we also swap the compare operands. It also switches
5134 // whether we return true for 'equality', so we compensate by picking the
5135 // opposite condition code to our original choice.
5136 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
5137 CC == ISD::SETUGT) {
5138 swpCmpOps = !swpCmpOps;
5139 swpVselOps = !swpVselOps;
5140 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
5141 }
5142
5143 // 'ordered' is 'anything but unordered', so use the VS condition code and
5144 // swap the VSEL operands.
5145 if (CC == ISD::SETO) {
5146 CondCode = ARMCC::VS;
5147 swpVselOps = true;
5148 }
5149
5150 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
5151 // code and swap the VSEL operands. Also do this if we don't care about the
5152 // unordered case.
5153 if (CC == ISD::SETUNE || CC == ISD::SETNE) {
5154 CondCode = ARMCC::EQ;
5155 swpVselOps = true;
5156 }
5157}
5158
5159SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
5160 SDValue TrueVal, SDValue ARMcc,
5161 SDValue Flags, SelectionDAG &DAG) const {
5162 if (!Subtarget->hasFP64() && VT == MVT::f64) {
5163 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
5164 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
5165 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
5166 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
5167
5168 SDValue TrueLow = TrueVal.getValue(0);
5169 SDValue TrueHigh = TrueVal.getValue(1);
5170 SDValue FalseLow = FalseVal.getValue(0);
5171 SDValue FalseHigh = FalseVal.getValue(1);
5172
5173 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
5174 ARMcc, Flags);
5175 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
5176 ARMcc, Flags);
5177
5178 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
5179 }
5180 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, Flags);
5181}
5182
5184 return CC == ISD::SETGT || CC == ISD::SETGE;
5185}
5186
5188 return CC == ISD::SETLT || CC == ISD::SETLE;
5189}
5190
5191// See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
5192// All of these conditions (and their <= and >= counterparts) will do:
5193// x < k ? k : x
5194// x > k ? x : k
5195// k < x ? x : k
5196// k > x ? k : x
5197static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
5198 const SDValue TrueVal, const SDValue FalseVal,
5199 const ISD::CondCode CC, const SDValue K) {
5200 return (isGTorGE(CC) &&
5201 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
5202 (isLTorLE(CC) &&
5203 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
5204}
5205
5206// Check if two chained conditionals could be converted into SSAT or USAT.
5207//
5208// SSAT can replace a set of two conditional selectors that bound a number to an
5209// interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
5210//
5211// x < -k ? -k : (x > k ? k : x)
5212// x < -k ? -k : (x < k ? x : k)
5213// x > -k ? (x > k ? k : x) : -k
5214// x < k ? (x < -k ? -k : x) : k
5215// etc.
5216//
5217// LLVM canonicalizes these to either a min(max()) or a max(min())
5218// pattern. This function tries to match one of these and will return a SSAT
5219// node if successful.
5220//
5221// USAT works similarly to SSAT but bounds on the interval [0, k] where k + 1
5222// is a power of 2.
5224 EVT VT = Op.getValueType();
5225 SDValue V1 = Op.getOperand(0);
5226 SDValue K1 = Op.getOperand(1);
5227 SDValue TrueVal1 = Op.getOperand(2);
5228 SDValue FalseVal1 = Op.getOperand(3);
5229 ISD::CondCode CC1 = Op.getOperandCondCode(4);
5230
5231 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
5232 if (Op2.getOpcode() != ISD::SELECT_CC)
5233 return SDValue();
5234
5235 SDValue V2 = Op2.getOperand(0);
5236 SDValue K2 = Op2.getOperand(1);
5237 SDValue TrueVal2 = Op2.getOperand(2);
5238 SDValue FalseVal2 = Op2.getOperand(3);
5239 ISD::CondCode CC2 = Op2.getOperandCondCode(4);
5240
5241 SDValue V1Tmp = V1;
5242 SDValue V2Tmp = V2;
5243
5244 // Check that the registers and the constants match a max(min()) or min(max())
5245 // pattern
5246 if (V1Tmp != TrueVal1 || V2Tmp != TrueVal2 || K1 != FalseVal1 ||
5247 K2 != FalseVal2 ||
5248 !((isGTorGE(CC1) && isLTorLE(CC2)) || (isLTorLE(CC1) && isGTorGE(CC2))))
5249 return SDValue();
5250
5251 // Check that the constant in the lower-bound check is
5252 // the opposite of the constant in the upper-bound check
5253 // in 1's complement.
5255 return SDValue();
5256
5257 int64_t Val1 = cast<ConstantSDNode>(K1)->getSExtValue();
5258 int64_t Val2 = cast<ConstantSDNode>(K2)->getSExtValue();
5259 int64_t PosVal = std::max(Val1, Val2);
5260 int64_t NegVal = std::min(Val1, Val2);
5261
5262 if (!((Val1 > Val2 && isLTorLE(CC1)) || (Val1 < Val2 && isLTorLE(CC2))) ||
5263 !isPowerOf2_64(PosVal + 1))
5264 return SDValue();
5265
5266 // Handle the difference between USAT (unsigned) and SSAT (signed)
5267 // saturation
5268 // At this point, PosVal is guaranteed to be positive
5269 uint64_t K = PosVal;
5270 SDLoc dl(Op);
5271 if (Val1 == ~Val2)
5272 return DAG.getNode(ARMISD::SSAT, dl, VT, V2Tmp,
5273 DAG.getConstant(llvm::countr_one(K), dl, VT));
5274 if (NegVal == 0)
5275 return DAG.getNode(ARMISD::USAT, dl, VT, V2Tmp,
5276 DAG.getConstant(llvm::countr_one(K), dl, VT));
5277
5278 return SDValue();
5279}
5280
5281// Check if a condition of the type x < k ? k : x can be converted into a
5282// bit operation instead of conditional moves.
5283// Currently this is allowed given:
5284// - The conditions and values match up
5285// - k is 0 or -1 (all ones)
5286// This function will not check the last condition, thats up to the caller
5287// It returns true if the transformation can be made, and in such case
5288// returns x in V, and k in SatK.
5290 SDValue &SatK)
5291{
5292 SDValue LHS = Op.getOperand(0);
5293 SDValue RHS = Op.getOperand(1);
5294 ISD::CondCode CC = Op.getOperandCondCode(4);
5295 SDValue TrueVal = Op.getOperand(2);
5296 SDValue FalseVal = Op.getOperand(3);
5297
5299 ? &RHS
5300 : nullptr;
5301
5302 // No constant operation in comparison, early out
5303 if (!K)
5304 return false;
5305
5306 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
5307 V = (KTmp == TrueVal) ? FalseVal : TrueVal;
5308 SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
5309
5310 // If the constant on left and right side, or variable on left and right,
5311 // does not match, early out
5312 if (*K != KTmp || V != VTmp)
5313 return false;
5314
5315 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
5316 SatK = *K;
5317 return true;
5318 }
5319
5320 return false;
5321}
5322
5323bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
5324 if (VT == MVT::f32)
5325 return !Subtarget->hasVFP2Base();
5326 if (VT == MVT::f64)
5327 return !Subtarget->hasFP64();
5328 if (VT == MVT::f16)
5329 return !Subtarget->hasFullFP16();
5330 return false;
5331}
5332
5333static SDValue matchCSET(unsigned &Opcode, bool &InvertCond, SDValue TrueVal,
5334 SDValue FalseVal, const ARMSubtarget *Subtarget) {
5335 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
5336 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
5337 if (!CFVal || !CTVal || !Subtarget->hasV8_1MMainlineOps())
5338 return SDValue();
5339
5340 unsigned TVal = CTVal->getZExtValue();
5341 unsigned FVal = CFVal->getZExtValue();
5342
5343 Opcode = 0;
5344 InvertCond = false;
5345 if (TVal == ~FVal) {
5346 Opcode = ARMISD::CSINV;
5347 } else if (TVal == ~FVal + 1) {
5348 Opcode = ARMISD::CSNEG;
5349 } else if (TVal + 1 == FVal) {
5350 Opcode = ARMISD::CSINC;
5351 } else if (TVal == FVal + 1) {
5352 Opcode = ARMISD::CSINC;
5353 std::swap(TrueVal, FalseVal);
5354 std::swap(TVal, FVal);
5355 InvertCond = !InvertCond;
5356 } else {
5357 return SDValue();
5358 }
5359
5360 // If one of the constants is cheaper than another, materialise the
5361 // cheaper one and let the csel generate the other.
5362 if (Opcode != ARMISD::CSINC &&
5364 std::swap(TrueVal, FalseVal);
5365 std::swap(TVal, FVal);
5366 InvertCond = !InvertCond;
5367 }
5368
5369 // Attempt to use ZR checking TVal is 0, possibly inverting the condition
5370 // to get there. CSINC not is invertable like the other two (~(~a) == a,
5371 // -(-a) == a, but (a+1)+1 != a).
5372 if (FVal == 0 && Opcode != ARMISD::CSINC) {
5373 std::swap(TrueVal, FalseVal);
5374 std::swap(TVal, FVal);
5375 InvertCond = !InvertCond;
5376 }
5377
5378 return TrueVal;
5379}
5380
5381SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5382 EVT VT = Op.getValueType();
5383 SDLoc dl(Op);
5384
5385 // Try to convert two saturating conditional selects into a single SSAT
5386 if ((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2())
5387 if (SDValue SatValue = LowerSaturatingConditional(Op, DAG))
5388 return SatValue;
5389
5390 // Try to convert expressions of the form x < k ? k : x (and similar forms)
5391 // into more efficient bit operations, which is possible when k is 0 or -1
5392 // On ARM and Thumb-2 which have flexible operand 2 this will result in
5393 // single instructions. On Thumb the shift and the bit operation will be two
5394 // instructions.
5395 // Only allow this transformation on full-width (32-bit) operations
5396 SDValue LowerSatConstant;
5397 SDValue SatValue;
5398 if (VT == MVT::i32 &&
5399 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
5400 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
5401 DAG.getConstant(31, dl, VT));
5402 if (isNullConstant(LowerSatConstant)) {
5403 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
5404 DAG.getAllOnesConstant(dl, VT));
5405 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
5406 } else if (isAllOnesConstant(LowerSatConstant))
5407 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
5408 }
5409
5410 SDValue LHS = Op.getOperand(0);
5411 SDValue RHS = Op.getOperand(1);
5412 ISD::CondCode CC = Op.getOperandCondCode(4);
5413 SDValue TrueVal = Op.getOperand(2);
5414 SDValue FalseVal = Op.getOperand(3);
5415 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
5416 ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
5417 if (Op.getValueType().isInteger()) {
5418
5419 // Check for SMAX(lhs, 0) and SMIN(lhs, 0) patterns.
5420 // (SELECT_CC setgt, lhs, 0, lhs, 0) -> (BIC lhs, (SRA lhs, typesize-1))
5421 // (SELECT_CC setlt, lhs, 0, lhs, 0) -> (AND lhs, (SRA lhs, typesize-1))
5422 // Both require less instructions than compare and conditional select.
5423 if ((CC == ISD::SETGT || CC == ISD::SETLT) && LHS == TrueVal && RHSC &&
5424 RHSC->isZero() && CFVal && CFVal->isZero() &&
5425 LHS.getValueType() == RHS.getValueType()) {
5426 EVT VT = LHS.getValueType();
5427 SDValue Shift =
5428 DAG.getNode(ISD::SRA, dl, VT, LHS,
5429 DAG.getConstant(VT.getSizeInBits() - 1, dl, VT));
5430
5431 if (CC == ISD::SETGT)
5432 Shift = DAG.getNOT(dl, Shift, VT);
5433
5434 return DAG.getNode(ISD::AND, dl, VT, LHS, Shift);
5435 }
5436
5437 // (SELECT_CC setlt, x, 0, 1, 0) -> SRL(x, bw-1)
5438 if (CC == ISD::SETLT && isNullConstant(RHS) && isOneConstant(TrueVal) &&
5439 isNullConstant(FalseVal) && LHS.getValueType() == VT)
5440 return DAG.getNode(ISD::SRL, dl, VT, LHS,
5441 DAG.getConstant(VT.getSizeInBits() - 1, dl, VT));
5442 }
5443
5444 if (LHS.getValueType() == MVT::i32) {
5445 unsigned Opcode;
5446 bool InvertCond;
5447 if (SDValue Op =
5448 matchCSET(Opcode, InvertCond, TrueVal, FalseVal, Subtarget)) {
5449 if (InvertCond)
5450 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5451
5452 SDValue ARMcc;
5453 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5454 EVT VT = Op.getValueType();
5455 return DAG.getNode(Opcode, dl, VT, Op, Op, ARMcc, Cmp);
5456 }
5457 }
5458
5459 if (isUnsupportedFloatingType(LHS.getValueType())) {
5460 softenSetCCOperands(DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5461
5462 // If softenSetCCOperands only returned one value, we should compare it to
5463 // zero.
5464 if (!RHS.getNode()) {
5465 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5466 CC = ISD::SETNE;
5467 }
5468 }
5469
5470 if (LHS.getValueType() == MVT::i32) {
5471 // Try to generate VSEL on ARMv8.
5472 // The VSEL instruction can't use all the usual ARM condition
5473 // codes: it only has two bits to select the condition code, so it's
5474 // constrained to use only GE, GT, VS and EQ.
5475 //
5476 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
5477 // swap the operands of the previous compare instruction (effectively
5478 // inverting the compare condition, swapping 'less' and 'greater') and
5479 // sometimes need to swap the operands to the VSEL (which inverts the
5480 // condition in the sense of firing whenever the previous condition didn't)
5481 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
5482 TrueVal.getValueType() == MVT::f32 ||
5483 TrueVal.getValueType() == MVT::f64)) {
5485 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
5486 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
5487 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5488 std::swap(TrueVal, FalseVal);
5489 }
5490 }
5491
5492 SDValue ARMcc;
5493 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5494 // Choose GE over PL, which vsel does now support
5495 if (ARMcc->getAsZExtVal() == ARMCC::PL)
5496 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
5497 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, Cmp, DAG);
5498 }
5499
5500 ARMCC::CondCodes CondCode, CondCode2;
5501 FPCCToARMCC(CC, CondCode, CondCode2);
5502
5503 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
5504 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
5505 // must use VSEL (limited condition codes), due to not having conditional f16
5506 // moves.
5507 if (Subtarget->hasFPARMv8Base() &&
5508 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
5509 (TrueVal.getValueType() == MVT::f16 ||
5510 TrueVal.getValueType() == MVT::f32 ||
5511 TrueVal.getValueType() == MVT::f64)) {
5512 bool swpCmpOps = false;
5513 bool swpVselOps = false;
5514 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
5515
5516 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
5517 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
5518 if (swpCmpOps)
5519 std::swap(LHS, RHS);
5520 if (swpVselOps)
5521 std::swap(TrueVal, FalseVal);
5522 }
5523 }
5524
5525 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5526 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5527 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, Cmp, DAG);
5528 if (CondCode2 != ARMCC::AL) {
5529 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
5530 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, Cmp, DAG);
5531 }
5532 return Result;
5533}
5534
5535/// canChangeToInt - Given the fp compare operand, return true if it is suitable
5536/// to morph to an integer compare sequence.
5537static bool canChangeToInt(SDValue Op, bool &SeenZero,
5538 const ARMSubtarget *Subtarget) {
5539 SDNode *N = Op.getNode();
5540 if (!N->hasOneUse())
5541 // Otherwise it requires moving the value from fp to integer registers.
5542 return false;
5543 if (!N->getNumValues())
5544 return false;
5545 EVT VT = Op.getValueType();
5546 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
5547 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
5548 // vmrs are very slow, e.g. cortex-a8.
5549 return false;
5550
5551 if (isFloatingPointZero(Op)) {
5552 SeenZero = true;
5553 return true;
5554 }
5555 return ISD::isNormalLoad(N);
5556}
5557
5560 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
5561
5563 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
5564 Ld->getPointerInfo(), Ld->getAlign(),
5565 Ld->getMemOperand()->getFlags());
5566
5567 llvm_unreachable("Unknown VFP cmp argument!");
5568}
5569
5571 SDValue &RetVal1, SDValue &RetVal2) {
5572 SDLoc dl(Op);
5573
5574 if (isFloatingPointZero(Op)) {
5575 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
5576 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
5577 return;
5578 }
5579
5580 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5581 SDValue Ptr = Ld->getBasePtr();
5582 RetVal1 =
5583 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5584 Ld->getAlign(), Ld->getMemOperand()->getFlags());
5585
5586 EVT PtrType = Ptr.getValueType();
5587 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5588 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5589 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5590 Ld->getPointerInfo().getWithOffset(4),
5591 commonAlignment(Ld->getAlign(), 4),
5592 Ld->getMemOperand()->getFlags());
5593 return;
5594 }
5595
5596 llvm_unreachable("Unknown VFP cmp argument!");
5597}
5598
5599/// OptimizeVFPBrcond - With nnan and without daz, it's legal to optimize some
5600/// f32 and even f64 comparisons to integer ones.
5601SDValue
5602ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5603 SDValue Chain = Op.getOperand(0);
5604 ISD::CondCode CC = Op.getOperandCondCode(1);
5605 SDValue LHS = Op.getOperand(2);
5606 SDValue RHS = Op.getOperand(3);
5607 SDValue Dest = Op.getOperand(4);
5608 SDLoc dl(Op);
5609
5610 bool LHSSeenZero = false;
5611 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5612 bool RHSSeenZero = false;
5613 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5614 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5615 // If unsafe fp math optimization is enabled and there are no other uses of
5616 // the CMP operands, and the condition code is EQ or NE, we can optimize it
5617 // to an integer comparison.
5618 if (CC == ISD::SETOEQ)
5619 CC = ISD::SETEQ;
5620 else if (CC == ISD::SETUNE)
5621 CC = ISD::SETNE;
5622
5623 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5624 SDValue ARMcc;
5625 if (LHS.getValueType() == MVT::f32) {
5626 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5627 bitcastf32Toi32(LHS, DAG), Mask);
5628 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5629 bitcastf32Toi32(RHS, DAG), Mask);
5630 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5631 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc,
5632 Cmp);
5633 }
5634
5635 SDValue LHS1, LHS2;
5636 SDValue RHS1, RHS2;
5637 expandf64Toi32(LHS, DAG, LHS1, LHS2);
5638 expandf64Toi32(RHS, DAG, RHS1, RHS2);
5639 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5640 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5642 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5643 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5644 return DAG.getNode(ARMISD::BCC_i64, dl, MVT::Other, Ops);
5645 }
5646
5647 return SDValue();
5648}
5649
5650// Generate CMP + CMOV for integer abs.
5651SDValue ARMTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
5652 SDLoc DL(Op);
5653
5654 SDValue Neg = DAG.getNegative(Op.getOperand(0), DL, MVT::i32);
5655
5656 // Generate CMP & CMOV.
5657 SDValue Cmp = DAG.getNode(ARMISD::CMP, DL, FlagsVT, Op.getOperand(0),
5658 DAG.getConstant(0, DL, MVT::i32));
5659 return DAG.getNode(ARMISD::CMOV, DL, MVT::i32, Op.getOperand(0), Neg,
5660 DAG.getConstant(ARMCC::MI, DL, MVT::i32), Cmp);
5661}
5662
5664 ARMCC::CondCodes CondCode =
5665 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
5666 CondCode = ARMCC::getOppositeCondition(CondCode);
5667 return DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5668}
5669
5670SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5671 SDValue Chain = Op.getOperand(0);
5672 SDValue Cond = Op.getOperand(1);
5673 SDValue Dest = Op.getOperand(2);
5674 SDLoc dl(Op);
5675
5676 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5677 // instruction.
5678 unsigned Opc = Cond.getOpcode();
5679 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5680 !Subtarget->isThumb1Only();
5681 if (Cond.getResNo() == 1 &&
5682 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5683 Opc == ISD::USUBO || OptimizeMul)) {
5684 // Only lower legal XALUO ops.
5685 if (!isTypeLegal(Cond->getValueType(0)))
5686 return SDValue();
5687
5688 // The actual operation with overflow check.
5689 SDValue Value, OverflowCmp;
5690 SDValue ARMcc;
5691 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5692
5693 // Reverse the condition code.
5694 ARMcc = getInvertedARMCondCode(ARMcc, DAG);
5695
5696 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc,
5697 OverflowCmp);
5698 }
5699
5700 return SDValue();
5701}
5702
5703SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5704 SDValue Chain = Op.getOperand(0);
5705 ISD::CondCode CC = Op.getOperandCondCode(1);
5706 SDValue LHS = Op.getOperand(2);
5707 SDValue RHS = Op.getOperand(3);
5708 SDValue Dest = Op.getOperand(4);
5709 SDLoc dl(Op);
5710
5711 if (isUnsupportedFloatingType(LHS.getValueType())) {
5712 softenSetCCOperands(DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5713
5714 // If softenSetCCOperands only returned one value, we should compare it to
5715 // zero.
5716 if (!RHS.getNode()) {
5717 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5718 CC = ISD::SETNE;
5719 }
5720 }
5721
5722 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5723 // instruction.
5724 unsigned Opc = LHS.getOpcode();
5725 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5726 !Subtarget->isThumb1Only();
5727 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5728 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5729 Opc == ISD::USUBO || OptimizeMul) &&
5730 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5731 // Only lower legal XALUO ops.
5732 if (!isTypeLegal(LHS->getValueType(0)))
5733 return SDValue();
5734
5735 // The actual operation with overflow check.
5736 SDValue Value, OverflowCmp;
5737 SDValue ARMcc;
5738 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5739
5740 if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5741 // Reverse the condition code.
5742 ARMcc = getInvertedARMCondCode(ARMcc, DAG);
5743 }
5744
5745 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc,
5746 OverflowCmp);
5747 }
5748
5749 if (LHS.getValueType() == MVT::i32) {
5750 SDValue ARMcc;
5751 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5752 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, Cmp);
5753 }
5754
5755 SDNodeFlags Flags = Op->getFlags();
5756 if (Flags.hasNoNaNs() &&
5757 DAG.getDenormalMode(MVT::f32) == DenormalMode::getIEEE() &&
5758 DAG.getDenormalMode(MVT::f64) == DenormalMode::getIEEE() &&
5759 (CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETNE ||
5760 CC == ISD::SETUNE)) {
5761 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5762 return Result;
5763 }
5764
5765 ARMCC::CondCodes CondCode, CondCode2;
5766 FPCCToARMCC(CC, CondCode, CondCode2);
5767
5768 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5769 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5770 SDValue Ops[] = {Chain, Dest, ARMcc, Cmp};
5771 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Ops);
5772 if (CondCode2 != ARMCC::AL) {
5773 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5774 SDValue Ops[] = {Res, Dest, ARMcc, Cmp};
5775 Res = DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Ops);
5776 }
5777 return Res;
5778}
5779
5780SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5781 SDValue Chain = Op.getOperand(0);
5782 SDValue Table = Op.getOperand(1);
5783 SDValue Index = Op.getOperand(2);
5784 SDLoc dl(Op);
5785
5786 EVT PTy = getPointerTy(DAG.getDataLayout());
5787 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5788 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5789 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5790 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5791 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5792 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5793 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5794 // which does another jump to the destination. This also makes it easier
5795 // to translate it to TBB / TBH later (Thumb2 only).
5796 // FIXME: This might not work if the function is extremely large.
5797 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5798 Addr, Op.getOperand(2), JTI);
5799 }
5800 if (isPositionIndependent() || Subtarget->isROPI()) {
5801 Addr =
5802 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5804 Chain = Addr.getValue(1);
5805 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5806 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5807 } else {
5808 Addr =
5809 DAG.getLoad(PTy, dl, Chain, Addr,
5811 Chain = Addr.getValue(1);
5812 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5813 }
5814}
5815
5817 EVT VT = Op.getValueType();
5818 SDLoc dl(Op);
5819
5820 if (Op.getValueType().getVectorElementType() == MVT::i32) {
5821 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5822 return Op;
5823 return DAG.UnrollVectorOp(Op.getNode());
5824 }
5825
5826 const bool HasFullFP16 = DAG.getSubtarget<ARMSubtarget>().hasFullFP16();
5827
5828 EVT NewTy;
5829 const EVT OpTy = Op.getOperand(0).getValueType();
5830 if (OpTy == MVT::v4f32)
5831 NewTy = MVT::v4i32;
5832 else if (OpTy == MVT::v4f16 && HasFullFP16)
5833 NewTy = MVT::v4i16;
5834 else if (OpTy == MVT::v8f16 && HasFullFP16)
5835 NewTy = MVT::v8i16;
5836 else
5837 llvm_unreachable("Invalid type for custom lowering!");
5838
5839 if (VT != MVT::v4i16 && VT != MVT::v8i16)
5840 return DAG.UnrollVectorOp(Op.getNode());
5841
5842 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5843 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5844}
5845
5846SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5847 EVT VT = Op.getValueType();
5848 if (VT.isVector())
5849 return LowerVectorFP_TO_INT(Op, DAG);
5850
5851 bool IsStrict = Op->isStrictFPOpcode();
5852 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
5853
5854 if (isUnsupportedFloatingType(SrcVal.getValueType())) {
5855 RTLIB::Libcall LC;
5856 if (Op.getOpcode() == ISD::FP_TO_SINT ||
5857 Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
5858 LC = RTLIB::getFPTOSINT(SrcVal.getValueType(),
5859 Op.getValueType());
5860 else
5861 LC = RTLIB::getFPTOUINT(SrcVal.getValueType(),
5862 Op.getValueType());
5863 SDLoc Loc(Op);
5864 MakeLibCallOptions CallOptions;
5865 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
5867 std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
5868 CallOptions, Loc, Chain);
5869 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
5870 }
5871
5872 return Op;
5873}
5874
5876 const ARMSubtarget *Subtarget) {
5877 EVT VT = Op.getValueType();
5878 EVT ToVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
5879 EVT FromVT = Op.getOperand(0).getValueType();
5880
5881 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f32)
5882 return Op;
5883 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f64 &&
5884 Subtarget->hasFP64())
5885 return Op;
5886 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f16 &&
5887 Subtarget->hasFullFP16())
5888 return Op;
5889 if (VT == MVT::v4i32 && ToVT == MVT::i32 && FromVT == MVT::v4f32 &&
5890 Subtarget->hasMVEFloatOps())
5891 return Op;
5892 if (VT == MVT::v8i16 && ToVT == MVT::i16 && FromVT == MVT::v8f16 &&
5893 Subtarget->hasMVEFloatOps())
5894 return Op;
5895
5896 if (FromVT != MVT::v4f32 && FromVT != MVT::v8f16)
5897 return SDValue();
5898
5899 SDLoc DL(Op);
5900 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
5901 unsigned BW = ToVT.getScalarSizeInBits() - IsSigned;
5902 SDValue CVT = DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
5903 DAG.getValueType(VT.getScalarType()));
5904 SDValue Max = DAG.getNode(IsSigned ? ISD::SMIN : ISD::UMIN, DL, VT, CVT,
5905 DAG.getConstant((1 << BW) - 1, DL, VT));
5906 if (IsSigned)
5907 Max = DAG.getNode(ISD::SMAX, DL, VT, Max,
5908 DAG.getSignedConstant(-(1 << BW), DL, VT));
5909 return Max;
5910}
5911
5913 EVT VT = Op.getValueType();
5914 SDLoc dl(Op);
5915
5916 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5917 if (VT.getVectorElementType() == MVT::f32)
5918 return Op;
5919 return DAG.UnrollVectorOp(Op.getNode());
5920 }
5921
5922 assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5923 Op.getOperand(0).getValueType() == MVT::v8i16) &&
5924 "Invalid type for custom lowering!");
5925
5926 const bool HasFullFP16 = DAG.getSubtarget<ARMSubtarget>().hasFullFP16();
5927
5928 EVT DestVecType;
5929 if (VT == MVT::v4f32)
5930 DestVecType = MVT::v4i32;
5931 else if (VT == MVT::v4f16 && HasFullFP16)
5932 DestVecType = MVT::v4i16;
5933 else if (VT == MVT::v8f16 && HasFullFP16)
5934 DestVecType = MVT::v8i16;
5935 else
5936 return DAG.UnrollVectorOp(Op.getNode());
5937
5938 unsigned CastOpc;
5939 unsigned Opc;
5940 switch (Op.getOpcode()) {
5941 default: llvm_unreachable("Invalid opcode!");
5942 case ISD::SINT_TO_FP:
5943 CastOpc = ISD::SIGN_EXTEND;
5945 break;
5946 case ISD::UINT_TO_FP:
5947 CastOpc = ISD::ZERO_EXTEND;
5949 break;
5950 }
5951
5952 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5953 return DAG.getNode(Opc, dl, VT, Op);
5954}
5955
5956SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5957 EVT VT = Op.getValueType();
5958 if (VT.isVector())
5959 return LowerVectorINT_TO_FP(Op, DAG);
5960
5961 bool IsStrict = Op->isStrictFPOpcode();
5962 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
5963
5964 if (isUnsupportedFloatingType(VT)) {
5965 RTLIB::Libcall LC;
5966 if (Op.getOpcode() == ISD::SINT_TO_FP ||
5967 Op.getOpcode() == ISD::STRICT_SINT_TO_FP)
5968 LC = RTLIB::getSINTTOFP(SrcVal.getValueType(), Op.getValueType());
5969 else
5970 LC = RTLIB::getUINTTOFP(SrcVal.getValueType(), Op.getValueType());
5971 SDLoc Loc(Op);
5972 MakeLibCallOptions CallOptions;
5973 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
5975 std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
5976 CallOptions, Loc, Chain);
5977 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
5978 }
5979
5980 return Op;
5981}
5982
5983SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5984 // Implement fcopysign with a fabs and a conditional fneg.
5985 SDValue Tmp0 = Op.getOperand(0);
5986 SDValue Tmp1 = Op.getOperand(1);
5987 SDLoc dl(Op);
5988 EVT VT = Op.getValueType();
5989 EVT SrcVT = Tmp1.getValueType();
5990 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5991 Tmp0.getOpcode() == ARMISD::VMOVDRR;
5992 bool UseNEON = !InGPR && Subtarget->hasNEON();
5993
5994 if (UseNEON) {
5995 // Use VBSL to copy the sign bit.
5996 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5997 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5998 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5999 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
6000 if (VT == MVT::f64)
6001 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
6002 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
6003 DAG.getConstant(32, dl, MVT::i32));
6004 else /*if (VT == MVT::f32)*/
6005 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
6006 if (SrcVT == MVT::f32) {
6007 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
6008 if (VT == MVT::f64)
6009 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
6010 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
6011 DAG.getConstant(32, dl, MVT::i32));
6012 } else if (VT == MVT::f32)
6013 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
6014 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
6015 DAG.getConstant(32, dl, MVT::i32));
6016 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
6017 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
6018
6020 dl, MVT::i32);
6021 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
6022 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
6023 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
6024
6025 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
6026 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
6027 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
6028 if (VT == MVT::f32) {
6029 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
6030 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
6031 DAG.getConstant(0, dl, MVT::i32));
6032 } else {
6033 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
6034 }
6035
6036 return Res;
6037 }
6038
6039 // Bitcast operand 1 to i32.
6040 if (SrcVT == MVT::f64)
6041 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
6042 Tmp1).getValue(1);
6043 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
6044
6045 // Or in the signbit with integer operations.
6046 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
6047 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
6048 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
6049 if (VT == MVT::f32) {
6050 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
6051 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
6052 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
6053 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
6054 }
6055
6056 // f64: Or the high part with signbit and then combine two parts.
6057 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
6058 Tmp0);
6059 SDValue Lo = Tmp0.getValue(0);
6060 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
6061 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
6062 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
6063}
6064
6065SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
6067 MachineFrameInfo &MFI = MF.getFrameInfo();
6068 MFI.setReturnAddressIsTaken(true);
6069
6070 EVT VT = Op.getValueType();
6071 SDLoc dl(Op);
6072 unsigned Depth = Op.getConstantOperandVal(0);
6073 if (Depth) {
6074 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6075 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
6076 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
6077 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
6078 MachinePointerInfo());
6079 }
6080
6081 // Return LR, which contains the return address. Mark it an implicit live-in.
6082 Register Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
6083 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
6084}
6085
6086SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
6087 const ARMBaseRegisterInfo &ARI =
6088 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
6090 MachineFrameInfo &MFI = MF.getFrameInfo();
6091 MFI.setFrameAddressIsTaken(true);
6092
6093 EVT VT = Op.getValueType();
6094 SDLoc dl(Op); // FIXME probably not meaningful
6095 unsigned Depth = Op.getConstantOperandVal(0);
6096 Register FrameReg = ARI.getFrameRegister(MF);
6097 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6098 while (Depth--)
6099 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
6100 MachinePointerInfo());
6101 return FrameAddr;
6102}
6103
6104// FIXME? Maybe this could be a TableGen attribute on some registers and
6105// this table could be generated automatically from RegInfo.
6106Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT,
6107 const MachineFunction &MF) const {
6108 return StringSwitch<Register>(RegName)
6109 .Case("sp", ARM::SP)
6110 .Default(Register());
6111}
6112
6113// Result is 64 bit value so split into two 32 bit values and return as a
6114// pair of values.
6116 SelectionDAG &DAG) {
6117 SDLoc DL(N);
6118
6119 // This function is only supposed to be called for i64 type destination.
6120 assert(N->getValueType(0) == MVT::i64
6121 && "ExpandREAD_REGISTER called for non-i64 type result.");
6122
6124 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
6125 N->getOperand(0),
6126 N->getOperand(1));
6127
6128 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
6129 Read.getValue(1)));
6130 Results.push_back(Read.getValue(2)); // Chain
6131}
6132
6133/// \p BC is a bitcast that is about to be turned into a VMOVDRR.
6134/// When \p DstVT, the destination type of \p BC, is on the vector
6135/// register bank and the source of bitcast, \p Op, operates on the same bank,
6136/// it might be possible to combine them, such that everything stays on the
6137/// vector register bank.
6138/// \p return The node that would replace \p BT, if the combine
6139/// is possible.
6141 SelectionDAG &DAG) {
6142 SDValue Op = BC->getOperand(0);
6143 EVT DstVT = BC->getValueType(0);
6144
6145 // The only vector instruction that can produce a scalar (remember,
6146 // since the bitcast was about to be turned into VMOVDRR, the source
6147 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
6148 // Moreover, we can do this combine only if there is one use.
6149 // Finally, if the destination type is not a vector, there is not
6150 // much point on forcing everything on the vector bank.
6151 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6152 !Op.hasOneUse())
6153 return SDValue();
6154
6155 // If the index is not constant, we will introduce an additional
6156 // multiply that will stick.
6157 // Give up in that case.
6158 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6159 if (!Index)
6160 return SDValue();
6161 unsigned DstNumElt = DstVT.getVectorNumElements();
6162
6163 // Compute the new index.
6164 const APInt &APIntIndex = Index->getAPIntValue();
6165 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
6166 NewIndex *= APIntIndex;
6167 // Check if the new constant index fits into i32.
6168 if (NewIndex.getBitWidth() > 32)
6169 return SDValue();
6170
6171 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
6172 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
6173 SDLoc dl(Op);
6174 SDValue ExtractSrc = Op.getOperand(0);
6175 EVT VecVT = EVT::getVectorVT(
6176 *DAG.getContext(), DstVT.getScalarType(),
6177 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
6178 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
6179 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
6180 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
6181}
6182
6183/// ExpandBITCAST - If the target supports VFP, this function is called to
6184/// expand a bit convert where either the source or destination type is i64 to
6185/// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
6186/// operand type is illegal (e.g., v2f32 for a target that doesn't support
6187/// vectors), since the legalizer won't know what to do with that.
6188SDValue ARMTargetLowering::ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
6189 const ARMSubtarget *Subtarget) const {
6190 SDLoc dl(N);
6191 SDValue Op = N->getOperand(0);
6192
6193 // This function is only supposed to be called for i16 and i64 types, either
6194 // as the source or destination of the bit convert.
6195 EVT SrcVT = Op.getValueType();
6196 EVT DstVT = N->getValueType(0);
6197
6198 if ((SrcVT == MVT::f16 || SrcVT == MVT::bf16) &&
6199 (DstVT == MVT::f16 || DstVT == MVT::bf16))
6200 return SDValue(N, 0);
6201
6202 if ((SrcVT == MVT::i16 || SrcVT == MVT::i32) &&
6203 (DstVT == MVT::f16 || DstVT == MVT::bf16)) {
6204 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), MVT::i32, Op);
6205 if (Subtarget->hasFullFP16())
6206 return DAG.getNode(ARMISD::VMOVhr, dl, DstVT, Ext);
6207 return DAG.getNode(ARMISD::VMOVsr, dl, DstVT, Ext);
6208 }
6209
6210 if ((DstVT == MVT::i16 || DstVT == MVT::i32) &&
6211 (SrcVT == MVT::f16 || SrcVT == MVT::bf16)) {
6212 if (Subtarget->hasFullFP16() && !Subtarget->hasBF16())
6213 Op = DAG.getBitcast(MVT::f16, Op);
6214 return DAG.getNode(
6215 ISD::TRUNCATE, SDLoc(N), DstVT,
6216 MoveFromHPR(SDLoc(N), DAG, MVT::i32, SrcVT.getSimpleVT(), Op));
6217 }
6218
6219 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
6220 return SDValue();
6221
6222 // Turn i64->f64 into VMOVDRR.
6223 if (SrcVT == MVT::i64 && isTypeLegal(DstVT)) {
6224 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
6225 // if we can combine the bitcast with its source.
6227 return Val;
6228 SDValue Lo, Hi;
6229 std::tie(Lo, Hi) = DAG.SplitScalar(Op, dl, MVT::i32, MVT::i32);
6230 return DAG.getNode(ISD::BITCAST, dl, DstVT,
6231 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
6232 }
6233
6234 // Turn f64->i64 into VMOVRRD.
6235 if (DstVT == MVT::i64 && isTypeLegal(SrcVT)) {
6236 SDValue Cvt;
6237 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
6238 SrcVT.getVectorNumElements() > 1)
6239 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6240 DAG.getVTList(MVT::i32, MVT::i32),
6241 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
6242 else
6243 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6244 DAG.getVTList(MVT::i32, MVT::i32), Op);
6245 // Merge the pieces into a single i64 value.
6246 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
6247 }
6248
6249 return SDValue();
6250}
6251
6252/// getZeroVector - Returns a vector of specified type with all zero elements.
6253/// Zero vectors are used to represent vector negation and in those cases
6254/// will be implemented with the NEON VNEG instruction. However, VNEG does
6255/// not support i64 elements, so sometimes the zero vectors will need to be
6256/// explicitly constructed. Regardless, use a canonical VMOV to create the
6257/// zero vector.
6258static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
6259 assert(VT.isVector() && "Expected a vector type");
6260 // The canonical modified immediate encoding of a zero vector is....0!
6261 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
6262 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
6263 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
6264 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6265}
6266
6267/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6268/// i32 values and take a 2 x i32 value to shift plus a shift amount.
6269SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
6270 SelectionDAG &DAG) const {
6271 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6272 EVT VT = Op.getValueType();
6273 unsigned VTBits = VT.getSizeInBits();
6274 SDLoc dl(Op);
6275 SDValue ShOpLo = Op.getOperand(0);
6276 SDValue ShOpHi = Op.getOperand(1);
6277 SDValue ShAmt = Op.getOperand(2);
6278 SDValue ARMcc;
6279 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6280
6281 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
6282
6283 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6284 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6285 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
6286 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6287 DAG.getConstant(VTBits, dl, MVT::i32));
6288 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
6289 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6290 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
6291 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6292 ISD::SETGE, ARMcc, DAG, dl);
6293 SDValue Lo =
6294 DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, ARMcc, CmpLo);
6295
6296 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
6297 SDValue HiBigShift = Opc == ISD::SRA
6298 ? DAG.getNode(Opc, dl, VT, ShOpHi,
6299 DAG.getConstant(VTBits - 1, dl, VT))
6300 : DAG.getConstant(0, dl, VT);
6301 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6302 ISD::SETGE, ARMcc, DAG, dl);
6303 SDValue Hi =
6304 DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, ARMcc, CmpHi);
6305
6306 SDValue Ops[2] = { Lo, Hi };
6307 return DAG.getMergeValues(Ops, dl);
6308}
6309
6310/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6311/// i32 values and take a 2 x i32 value to shift plus a shift amount.
6312SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
6313 SelectionDAG &DAG) const {
6314 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6315 EVT VT = Op.getValueType();
6316 unsigned VTBits = VT.getSizeInBits();
6317 SDLoc dl(Op);
6318 SDValue ShOpLo = Op.getOperand(0);
6319 SDValue ShOpHi = Op.getOperand(1);
6320 SDValue ShAmt = Op.getOperand(2);
6321 SDValue ARMcc;
6322
6323 assert(Op.getOpcode() == ISD::SHL_PARTS);
6324 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6325 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6326 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
6327 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
6328 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6329
6330 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6331 DAG.getConstant(VTBits, dl, MVT::i32));
6332 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
6333 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6334 ISD::SETGE, ARMcc, DAG, dl);
6335 SDValue Hi =
6336 DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, ARMcc, CmpHi);
6337
6338 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6339 ISD::SETGE, ARMcc, DAG, dl);
6340 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6341 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
6342 DAG.getConstant(0, dl, VT), ARMcc, CmpLo);
6343
6344 SDValue Ops[2] = { Lo, Hi };
6345 return DAG.getMergeValues(Ops, dl);
6346}
6347
6348SDValue ARMTargetLowering::LowerGET_ROUNDING(SDValue Op,
6349 SelectionDAG &DAG) const {
6350 // The rounding mode is in bits 23:22 of the FPSCR.
6351 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
6352 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
6353 // so that the shift + and get folded into a bitfield extract.
6354 SDLoc dl(Op);
6355 SDValue Chain = Op.getOperand(0);
6356 SDValue Ops[] = {Chain,
6357 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32)};
6358
6359 SDValue FPSCR =
6360 DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, {MVT::i32, MVT::Other}, Ops);
6361 Chain = FPSCR.getValue(1);
6362 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
6363 DAG.getConstant(1U << 22, dl, MVT::i32));
6364 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
6365 DAG.getConstant(22, dl, MVT::i32));
6366 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
6367 DAG.getConstant(3, dl, MVT::i32));
6368 return DAG.getMergeValues({And, Chain}, dl);
6369}
6370
6371SDValue ARMTargetLowering::LowerSET_ROUNDING(SDValue Op,
6372 SelectionDAG &DAG) const {
6373 SDLoc DL(Op);
6374 SDValue Chain = Op->getOperand(0);
6375 SDValue RMValue = Op->getOperand(1);
6376
6377 // The rounding mode is in bits 23:22 of the FPSCR.
6378 // The llvm.set.rounding argument value to ARM rounding mode value mapping
6379 // is 0->3, 1->0, 2->1, 3->2. The formula we use to implement this is
6380 // ((arg - 1) & 3) << 22).
6381 //
6382 // It is expected that the argument of llvm.set.rounding is within the
6383 // segment [0, 3], so NearestTiesToAway (4) is not handled here. It is
6384 // responsibility of the code generated llvm.set.rounding to ensure this
6385 // condition.
6386
6387 // Calculate new value of FPSCR[23:22].
6388 RMValue = DAG.getNode(ISD::SUB, DL, MVT::i32, RMValue,
6389 DAG.getConstant(1, DL, MVT::i32));
6390 RMValue = DAG.getNode(ISD::AND, DL, MVT::i32, RMValue,
6391 DAG.getConstant(0x3, DL, MVT::i32));
6392 RMValue = DAG.getNode(ISD::SHL, DL, MVT::i32, RMValue,
6393 DAG.getConstant(ARM::RoundingBitsPos, DL, MVT::i32));
6394
6395 // Get current value of FPSCR.
6396 SDValue Ops[] = {Chain,
6397 DAG.getConstant(Intrinsic::arm_get_fpscr, DL, MVT::i32)};
6398 SDValue FPSCR =
6399 DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i32, MVT::Other}, Ops);
6400 Chain = FPSCR.getValue(1);
6401 FPSCR = FPSCR.getValue(0);
6402
6403 // Put new rounding mode into FPSCR[23:22].
6404 const unsigned RMMask = ~(ARM::Rounding::rmMask << ARM::RoundingBitsPos);
6405 FPSCR = DAG.getNode(ISD::AND, DL, MVT::i32, FPSCR,
6406 DAG.getConstant(RMMask, DL, MVT::i32));
6407 FPSCR = DAG.getNode(ISD::OR, DL, MVT::i32, FPSCR, RMValue);
6408 SDValue Ops2[] = {
6409 Chain, DAG.getConstant(Intrinsic::arm_set_fpscr, DL, MVT::i32), FPSCR};
6410 return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
6411}
6412
6413SDValue ARMTargetLowering::LowerSET_FPMODE(SDValue Op,
6414 SelectionDAG &DAG) const {
6415 SDLoc DL(Op);
6416 SDValue Chain = Op->getOperand(0);
6417 SDValue Mode = Op->getOperand(1);
6418
6419 // Generate nodes to build:
6420 // FPSCR = (FPSCR & FPStatusBits) | (Mode & ~FPStatusBits)
6421 SDValue Ops[] = {Chain,
6422 DAG.getConstant(Intrinsic::arm_get_fpscr, DL, MVT::i32)};
6423 SDValue FPSCR =
6424 DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i32, MVT::Other}, Ops);
6425 Chain = FPSCR.getValue(1);
6426 FPSCR = FPSCR.getValue(0);
6427
6428 SDValue FPSCRMasked =
6429 DAG.getNode(ISD::AND, DL, MVT::i32, FPSCR,
6430 DAG.getConstant(ARM::FPStatusBits, DL, MVT::i32));
6431 SDValue InputMasked =
6432 DAG.getNode(ISD::AND, DL, MVT::i32, Mode,
6433 DAG.getConstant(~ARM::FPStatusBits, DL, MVT::i32));
6434 FPSCR = DAG.getNode(ISD::OR, DL, MVT::i32, FPSCRMasked, InputMasked);
6435
6436 SDValue Ops2[] = {
6437 Chain, DAG.getConstant(Intrinsic::arm_set_fpscr, DL, MVT::i32), FPSCR};
6438 return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
6439}
6440
6441SDValue ARMTargetLowering::LowerRESET_FPMODE(SDValue Op,
6442 SelectionDAG &DAG) const {
6443 SDLoc DL(Op);
6444 SDValue Chain = Op->getOperand(0);
6445
6446 // To get the default FP mode all control bits are cleared:
6447 // FPSCR = FPSCR & (FPStatusBits | FPReservedBits)
6448 SDValue Ops[] = {Chain,
6449 DAG.getConstant(Intrinsic::arm_get_fpscr, DL, MVT::i32)};
6450 SDValue FPSCR =
6451 DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i32, MVT::Other}, Ops);
6452 Chain = FPSCR.getValue(1);
6453 FPSCR = FPSCR.getValue(0);
6454
6455 SDValue FPSCRMasked = DAG.getNode(
6456 ISD::AND, DL, MVT::i32, FPSCR,
6458 SDValue Ops2[] = {Chain,
6459 DAG.getConstant(Intrinsic::arm_set_fpscr, DL, MVT::i32),
6460 FPSCRMasked};
6461 return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
6462}
6463
6465 const ARMSubtarget *ST) {
6466 SDLoc dl(N);
6467 EVT VT = N->getValueType(0);
6468 if (VT.isVector() && ST->hasNEON()) {
6469
6470 // Compute the least significant set bit: LSB = X & -X
6471 SDValue X = N->getOperand(0);
6472 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
6473 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
6474
6476
6477 if (ElemTy == MVT::i8) {
6478 // Compute with: cttz(x) = ctpop(lsb - 1)
6479 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6480 DAG.getTargetConstant(1, dl, ElemTy));
6481 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6482 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6483 }
6484
6485 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
6486 (N->getOpcode() == ISD::CTTZ_ZERO_POISON)) {
6487 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
6488 unsigned NumBits = ElemTy.getSizeInBits();
6489 SDValue WidthMinus1 =
6490 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6491 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
6492 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
6493 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
6494 }
6495
6496 // Compute with: cttz(x) = ctpop(lsb - 1)
6497
6498 // Compute LSB - 1.
6499 SDValue Bits;
6500 if (ElemTy == MVT::i64) {
6501 // Load constant 0xffff'ffff'ffff'ffff to register.
6502 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6503 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
6504 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
6505 } else {
6506 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6507 DAG.getTargetConstant(1, dl, ElemTy));
6508 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6509 }
6510 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6511 }
6512
6513 if (!ST->hasV6T2Ops())
6514 return SDValue();
6515
6516 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
6517 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
6518}
6519
6521 const ARMSubtarget *ST) {
6522 EVT VT = N->getValueType(0);
6523 SDLoc DL(N);
6524
6525 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
6526 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
6527 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
6528 "Unexpected type for custom ctpop lowering");
6529
6531 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
6532 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
6533 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
6534
6535 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
6536 unsigned EltSize = 8;
6537 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
6538 while (EltSize != VT.getScalarSizeInBits()) {
6540 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
6541 TLI.getPointerTy(DAG.getDataLayout())));
6542 Ops.push_back(Res);
6543
6544 EltSize *= 2;
6545 NumElts /= 2;
6546 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
6547 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
6548 }
6549
6550 return Res;
6551}
6552
6553/// Getvshiftimm - Check if this is a valid build_vector for the immediate
6554/// operand of a vector shift operation, where all the elements of the
6555/// build_vector must have the same constant integer value.
6556static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6557 // Ignore bit_converts.
6558 while (Op.getOpcode() == ISD::BITCAST)
6559 Op = Op.getOperand(0);
6561 APInt SplatBits, SplatUndef;
6562 unsigned SplatBitSize;
6563 bool HasAnyUndefs;
6564 if (!BVN ||
6565 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
6566 ElementBits) ||
6567 SplatBitSize > ElementBits)
6568 return false;
6569 Cnt = SplatBits.getSExtValue();
6570 return true;
6571}
6572
6573/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6574/// operand of a vector shift left operation. That value must be in the range:
6575/// 0 <= Value < ElementBits for a left shift; or
6576/// 0 <= Value <= ElementBits for a long left shift.
6577static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6578 assert(VT.isVector() && "vector shift count is not a vector type");
6579 int64_t ElementBits = VT.getScalarSizeInBits();
6580 if (!getVShiftImm(Op, ElementBits, Cnt))
6581 return false;
6582 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6583}
6584
6585/// isVShiftRImm - Check if this is a valid build_vector for the immediate
6586/// operand of a vector shift right operation. For a shift opcode, the value
6587/// is positive, but for an intrinsic the value count must be negative. The
6588/// absolute value must be in the range:
6589/// 1 <= |Value| <= ElementBits for a right shift; or
6590/// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
6591static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6592 int64_t &Cnt) {
6593 assert(VT.isVector() && "vector shift count is not a vector type");
6594 int64_t ElementBits = VT.getScalarSizeInBits();
6595 if (!getVShiftImm(Op, ElementBits, Cnt))
6596 return false;
6597 if (!isIntrinsic)
6598 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6599 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
6600 Cnt = -Cnt;
6601 return true;
6602 }
6603 return false;
6604}
6605
6607 const ARMSubtarget *ST) {
6608 EVT VT = N->getValueType(0);
6609 SDLoc dl(N);
6610 int64_t Cnt;
6611
6612 if (!VT.isVector())
6613 return SDValue();
6614
6615 // We essentially have two forms here. Shift by an immediate and shift by a
6616 // vector register (there are also shift by a gpr, but that is just handled
6617 // with a tablegen pattern). We cannot easily match shift by an immediate in
6618 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
6619 // For shifting by a vector, we don't have VSHR, only VSHL (which can be
6620 // signed or unsigned, and a negative shift indicates a shift right).
6621 if (N->getOpcode() == ISD::SHL) {
6622 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
6623 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
6624 DAG.getConstant(Cnt, dl, MVT::i32));
6625 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
6626 N->getOperand(1));
6627 }
6628
6629 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
6630 "unexpected vector shift opcode");
6631
6632 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
6633 unsigned VShiftOpc =
6634 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
6635 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
6636 DAG.getConstant(Cnt, dl, MVT::i32));
6637 }
6638
6639 // Other right shifts we don't have operations for (we use a shift left by a
6640 // negative number).
6641 EVT ShiftVT = N->getOperand(1).getValueType();
6642 SDValue NegatedCount = DAG.getNode(
6643 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
6644 unsigned VShiftOpc =
6645 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
6646 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
6647}
6648
6650 const ARMSubtarget *ST) {
6651 EVT VT = N->getValueType(0);
6652 SDLoc dl(N);
6653
6654 // We can get here for a node like i32 = ISD::SHL i32, i64
6655 if (VT != MVT::i64)
6656 return SDValue();
6657
6658 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
6659 N->getOpcode() == ISD::SHL) &&
6660 "Unknown shift to lower!");
6661
6662 unsigned ShOpc = N->getOpcode();
6663 if (ST->hasMVEIntegerOps()) {
6664 SDValue ShAmt = N->getOperand(1);
6665 unsigned ShPartsOpc = ARMISD::LSLL;
6667
6668 // If the shift amount is greater than 32 or has a greater bitwidth than 64
6669 // then do the default optimisation
6670 if ((!Con && ShAmt->getValueType(0).getSizeInBits() > 64) ||
6671 (Con && (Con->getAPIntValue() == 0 || Con->getAPIntValue().uge(32))))
6672 return SDValue();
6673
6674 // Extract the lower 32 bits of the shift amount if it's not an i32
6675 if (ShAmt->getValueType(0) != MVT::i32)
6676 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6677
6678 if (ShOpc == ISD::SRL) {
6679 if (!Con)
6680 // There is no t2LSRLr instruction so negate and perform an lsll if the
6681 // shift amount is in a register, emulating a right shift.
6682 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6683 DAG.getConstant(0, dl, MVT::i32), ShAmt);
6684 else
6685 // Else generate an lsrl on the immediate shift amount
6686 ShPartsOpc = ARMISD::LSRL;
6687 } else if (ShOpc == ISD::SRA)
6688 ShPartsOpc = ARMISD::ASRL;
6689
6690 // Split Lower/Upper 32 bits of the destination/source
6691 SDValue Lo, Hi;
6692 std::tie(Lo, Hi) =
6693 DAG.SplitScalar(N->getOperand(0), dl, MVT::i32, MVT::i32);
6694 // Generate the shift operation as computed above
6695 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6696 ShAmt);
6697 // The upper 32 bits come from the second return value of lsll
6698 Hi = SDValue(Lo.getNode(), 1);
6699 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6700 }
6701
6702 // We only lower SRA, SRL of 1 here, all others use generic lowering.
6703 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6704 return SDValue();
6705
6706 // If we are in thumb mode, we don't have RRX.
6707 if (ST->isThumb1Only())
6708 return SDValue();
6709
6710 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
6711 SDValue Lo, Hi;
6712 std::tie(Lo, Hi) = DAG.SplitScalar(N->getOperand(0), dl, MVT::i32, MVT::i32);
6713
6714 // First, build a LSRS1/ASRS1 op, which shifts the top part by one and
6715 // captures the shifted out bit into a carry flag.
6716 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::LSRS1 : ARMISD::ASRS1;
6717 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, FlagsVT), Hi);
6718
6719 // The low part is an ARMISD::RRX operand, which shifts the carry in.
6720 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6721
6722 // Merge the pieces into a single i64 value.
6723 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6724}
6725
6727 const ARMSubtarget *ST) {
6728 bool Invert = false;
6729 bool Swap = false;
6730 unsigned Opc = ARMCC::AL;
6731
6732 SDValue Op0 = Op.getOperand(0);
6733 SDValue Op1 = Op.getOperand(1);
6734 SDValue CC = Op.getOperand(2);
6735 EVT VT = Op.getValueType();
6736 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6737 SDLoc dl(Op);
6738
6739 EVT CmpVT;
6740 if (ST->hasNEON())
6742 else {
6743 assert(ST->hasMVEIntegerOps() &&
6744 "No hardware support for integer vector comparison!");
6745
6746 if (Op.getValueType().getVectorElementType() != MVT::i1)
6747 return SDValue();
6748
6749 // Make sure we expand floating point setcc to scalar if we do not have
6750 // mve.fp, so that we can handle them from there.
6751 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6752 return SDValue();
6753
6754 CmpVT = VT;
6755 }
6756
6757 if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6758 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6759 // Special-case integer 64-bit equality comparisons. They aren't legal,
6760 // but they can be lowered with a few vector instructions.
6761 unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6762 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6763 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6764 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6765 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6766 DAG.getCondCode(ISD::SETEQ));
6767 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6768 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6769 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6770 if (SetCCOpcode == ISD::SETNE)
6771 Merged = DAG.getNOT(dl, Merged, CmpVT);
6772 Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6773 return Merged;
6774 }
6775
6776 if (CmpVT.getVectorElementType() == MVT::i64)
6777 // 64-bit comparisons are not legal in general.
6778 return SDValue();
6779
6780 if (Op1.getValueType().isFloatingPoint()) {
6781 switch (SetCCOpcode) {
6782 default: llvm_unreachable("Illegal FP comparison");
6783 case ISD::SETUNE:
6784 case ISD::SETNE:
6785 if (ST->hasMVEFloatOps()) {
6786 Opc = ARMCC::NE; break;
6787 } else {
6788 Invert = true; [[fallthrough]];
6789 }
6790 case ISD::SETOEQ:
6791 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6792 case ISD::SETOLT:
6793 case ISD::SETLT: Swap = true; [[fallthrough]];
6794 case ISD::SETOGT:
6795 case ISD::SETGT: Opc = ARMCC::GT; break;
6796 case ISD::SETOLE:
6797 case ISD::SETLE: Swap = true; [[fallthrough]];
6798 case ISD::SETOGE:
6799 case ISD::SETGE: Opc = ARMCC::GE; break;
6800 case ISD::SETUGE: Swap = true; [[fallthrough]];
6801 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6802 case ISD::SETUGT: Swap = true; [[fallthrough]];
6803 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6804 case ISD::SETUEQ: Invert = true; [[fallthrough]];
6805 case ISD::SETONE: {
6806 // Expand this to (OLT | OGT).
6807 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6808 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6809 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6810 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6811 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6812 if (Invert)
6813 Result = DAG.getNOT(dl, Result, VT);
6814 return Result;
6815 }
6816 case ISD::SETUO: Invert = true; [[fallthrough]];
6817 case ISD::SETO: {
6818 // Expand this to (OLT | OGE).
6819 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6820 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6821 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6822 DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6823 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6824 if (Invert)
6825 Result = DAG.getNOT(dl, Result, VT);
6826 return Result;
6827 }
6828 }
6829 } else {
6830 // Integer comparisons.
6831 switch (SetCCOpcode) {
6832 default: llvm_unreachable("Illegal integer comparison");
6833 case ISD::SETNE:
6834 if (ST->hasMVEIntegerOps()) {
6835 Opc = ARMCC::NE; break;
6836 } else {
6837 Invert = true; [[fallthrough]];
6838 }
6839 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6840 case ISD::SETLT: Swap = true; [[fallthrough]];
6841 case ISD::SETGT: Opc = ARMCC::GT; break;
6842 case ISD::SETLE: Swap = true; [[fallthrough]];
6843 case ISD::SETGE: Opc = ARMCC::GE; break;
6844 case ISD::SETULT: Swap = true; [[fallthrough]];
6845 case ISD::SETUGT: Opc = ARMCC::HI; break;
6846 case ISD::SETULE: Swap = true; [[fallthrough]];
6847 case ISD::SETUGE: Opc = ARMCC::HS; break;
6848 }
6849
6850 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6851 if (ST->hasNEON() && Opc == ARMCC::EQ) {
6852 SDValue AndOp;
6854 AndOp = Op0;
6855 else if (ISD::isBuildVectorAllZeros(Op0))
6856 AndOp = Op1;
6857
6858 // Ignore bitconvert.
6859 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6860 AndOp = AndOp.getOperand(0);
6861
6862 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6863 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6864 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6865 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6866 if (!Invert)
6867 Result = DAG.getNOT(dl, Result, VT);
6868 return Result;
6869 }
6870 }
6871 }
6872
6873 if (Swap)
6874 std::swap(Op0, Op1);
6875
6876 // If one of the operands is a constant vector zero, attempt to fold the
6877 // comparison to a specialized compare-against-zero form.
6878 if (ISD::isBuildVectorAllZeros(Op0) &&
6879 (Opc == ARMCC::GE || Opc == ARMCC::GT || Opc == ARMCC::EQ ||
6880 Opc == ARMCC::NE)) {
6881 if (Opc == ARMCC::GE)
6882 Opc = ARMCC::LE;
6883 else if (Opc == ARMCC::GT)
6884 Opc = ARMCC::LT;
6885 std::swap(Op0, Op1);
6886 }
6887
6888 SDValue Result;
6889 if (ISD::isBuildVectorAllZeros(Op1) &&
6890 (Opc == ARMCC::GE || Opc == ARMCC::GT || Opc == ARMCC::LE ||
6891 Opc == ARMCC::LT || Opc == ARMCC::NE || Opc == ARMCC::EQ))
6892 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, Op0,
6893 DAG.getConstant(Opc, dl, MVT::i32));
6894 else
6895 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6896 DAG.getConstant(Opc, dl, MVT::i32));
6897
6898 Result = DAG.getSExtOrTrunc(Result, dl, VT);
6899
6900 if (Invert)
6901 Result = DAG.getNOT(dl, Result, VT);
6902
6903 return Result;
6904}
6905
6907 SDValue LHS = Op.getOperand(0);
6908 SDValue RHS = Op.getOperand(1);
6909
6910 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6911
6912 SDValue Carry = Op.getOperand(2);
6913 SDValue Cond = Op.getOperand(3);
6914 SDLoc DL(Op);
6915
6916 // ARMISD::SUBE expects a carry not a borrow like ISD::USUBO_CARRY so we
6917 // have to invert the carry first.
6918 SDValue InvCarry = valueToCarryFlag(Carry, DAG, true);
6919
6920 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6921 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, InvCarry);
6922
6923 SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6924 SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6925 SDValue ARMcc = DAG.getConstant(
6926 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6927 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6928 Cmp.getValue(1));
6929}
6930
6931/// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6932/// valid vector constant for a NEON or MVE instruction with a "modified
6933/// immediate" operand (e.g., VMOV). If so, return the encoded value.
6934static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6935 unsigned SplatBitSize, SelectionDAG &DAG,
6936 const SDLoc &dl, EVT &VT, EVT VectorVT,
6937 VMOVModImmType type) {
6938 unsigned OpCmode, Imm;
6939 bool is128Bits = VectorVT.is128BitVector();
6940
6941 // SplatBitSize is set to the smallest size that splats the vector, so a
6942 // zero vector will always have SplatBitSize == 8. However, NEON modified
6943 // immediate instructions others than VMOV do not support the 8-bit encoding
6944 // of a zero vector, and the default encoding of zero is supposed to be the
6945 // 32-bit version.
6946 if (SplatBits == 0)
6947 SplatBitSize = 32;
6948
6949 switch (SplatBitSize) {
6950 case 8:
6951 if (type != VMOVModImm)
6952 return SDValue();
6953 // Any 1-byte value is OK. Op=0, Cmode=1110.
6954 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6955 OpCmode = 0xe;
6956 Imm = SplatBits;
6957 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6958 break;
6959
6960 case 16:
6961 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6962 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6963 if ((SplatBits & ~0xff) == 0) {
6964 // Value = 0x00nn: Op=x, Cmode=100x.
6965 OpCmode = 0x8;
6966 Imm = SplatBits;
6967 break;
6968 }
6969 if ((SplatBits & ~0xff00) == 0) {
6970 // Value = 0xnn00: Op=x, Cmode=101x.
6971 OpCmode = 0xa;
6972 Imm = SplatBits >> 8;
6973 break;
6974 }
6975 return SDValue();
6976
6977 case 32:
6978 // NEON's 32-bit VMOV supports splat values where:
6979 // * only one byte is nonzero, or
6980 // * the least significant byte is 0xff and the second byte is nonzero, or
6981 // * the least significant 2 bytes are 0xff and the third is nonzero.
6982 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6983 if ((SplatBits & ~0xff) == 0) {
6984 // Value = 0x000000nn: Op=x, Cmode=000x.
6985 OpCmode = 0;
6986 Imm = SplatBits;
6987 break;
6988 }
6989 if ((SplatBits & ~0xff00) == 0) {
6990 // Value = 0x0000nn00: Op=x, Cmode=001x.
6991 OpCmode = 0x2;
6992 Imm = SplatBits >> 8;
6993 break;
6994 }
6995 if ((SplatBits & ~0xff0000) == 0) {
6996 // Value = 0x00nn0000: Op=x, Cmode=010x.
6997 OpCmode = 0x4;
6998 Imm = SplatBits >> 16;
6999 break;
7000 }
7001 if ((SplatBits & ~0xff000000) == 0) {
7002 // Value = 0xnn000000: Op=x, Cmode=011x.
7003 OpCmode = 0x6;
7004 Imm = SplatBits >> 24;
7005 break;
7006 }
7007
7008 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
7009 if (type == OtherModImm) return SDValue();
7010
7011 if ((SplatBits & ~0xffff) == 0 &&
7012 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
7013 // Value = 0x0000nnff: Op=x, Cmode=1100.
7014 OpCmode = 0xc;
7015 Imm = SplatBits >> 8;
7016 break;
7017 }
7018
7019 // cmode == 0b1101 is not supported for MVE VMVN
7020 if (type == MVEVMVNModImm)
7021 return SDValue();
7022
7023 if ((SplatBits & ~0xffffff) == 0 &&
7024 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
7025 // Value = 0x00nnffff: Op=x, Cmode=1101.
7026 OpCmode = 0xd;
7027 Imm = SplatBits >> 16;
7028 break;
7029 }
7030
7031 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
7032 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
7033 // VMOV.I32. A (very) minor optimization would be to replicate the value
7034 // and fall through here to test for a valid 64-bit splat. But, then the
7035 // caller would also need to check and handle the change in size.
7036 return SDValue();
7037
7038 case 64: {
7039 if (type != VMOVModImm)
7040 return SDValue();
7041 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
7042 uint64_t BitMask = 0xff;
7043 unsigned ImmMask = 1;
7044 Imm = 0;
7045 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
7046 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
7047 Imm |= ImmMask;
7048 } else if ((SplatBits & BitMask) != 0) {
7049 return SDValue();
7050 }
7051 BitMask <<= 8;
7052 ImmMask <<= 1;
7053 }
7054
7055 // Op=1, Cmode=1110.
7056 OpCmode = 0x1e;
7057 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
7058 break;
7059 }
7060
7061 default:
7062 llvm_unreachable("unexpected size for isVMOVModifiedImm");
7063 }
7064
7065 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
7066 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
7067}
7068
7069SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
7070 const ARMSubtarget *ST) const {
7071 EVT VT = Op.getValueType();
7072 bool IsDouble = (VT == MVT::f64);
7073 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
7074 const APFloat &FPVal = CFP->getValueAPF();
7075
7076 // Prevent floating-point constants from using literal loads
7077 // when execute-only is enabled.
7078 if (ST->genExecuteOnly()) {
7079 // We shouldn't trigger this for v6m execute-only
7080 assert((!ST->isThumb1Only() || ST->hasV8MBaselineOps()) &&
7081 "Unexpected architecture");
7082
7083 // If we can represent the constant as an immediate, don't lower it
7084 if (isFPImmLegal(FPVal, VT))
7085 return Op;
7086 // Otherwise, construct as integer, and move to float register
7087 APInt INTVal = FPVal.bitcastToAPInt();
7088 SDLoc DL(CFP);
7089 switch (VT.getSimpleVT().SimpleTy) {
7090 default:
7091 llvm_unreachable("Unknown floating point type!");
7092 break;
7093 case MVT::f64: {
7094 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
7095 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
7096 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
7097 }
7098 case MVT::f32:
7099 return DAG.getNode(ARMISD::VMOVsr, DL, VT,
7100 DAG.getConstant(INTVal, DL, MVT::i32));
7101 }
7102 }
7103
7104 if (!ST->hasVFP3Base())
7105 return SDValue();
7106
7107 // Use the default (constant pool) lowering for double constants when we have
7108 // an SP-only FPU
7109 if (IsDouble && !Subtarget->hasFP64())
7110 return SDValue();
7111
7112 // Try splatting with a VMOV.f32...
7113 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
7114
7115 if (ImmVal != -1) {
7116 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
7117 // We have code in place to select a valid ConstantFP already, no need to
7118 // do any mangling.
7119 return Op;
7120 }
7121
7122 // It's a float and we are trying to use NEON operations where
7123 // possible. Lower it to a splat followed by an extract.
7124 SDLoc DL(Op);
7125 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
7126 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
7127 NewVal);
7128 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
7129 DAG.getConstant(0, DL, MVT::i32));
7130 }
7131
7132 // The rest of our options are NEON only, make sure that's allowed before
7133 // proceeding..
7134 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
7135 return SDValue();
7136
7137 EVT VMovVT;
7138 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
7139
7140 // It wouldn't really be worth bothering for doubles except for one very
7141 // important value, which does happen to match: 0.0. So make sure we don't do
7142 // anything stupid.
7143 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
7144 return SDValue();
7145
7146 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
7147 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
7148 VMovVT, VT, VMOVModImm);
7149 if (NewVal != SDValue()) {
7150 SDLoc DL(Op);
7151 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
7152 NewVal);
7153 if (IsDouble)
7154 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
7155
7156 // It's a float: cast and extract a vector element.
7157 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
7158 VecConstant);
7159 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
7160 DAG.getConstant(0, DL, MVT::i32));
7161 }
7162
7163 // Finally, try a VMVN.i32
7164 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
7165 VT, VMVNModImm);
7166 if (NewVal != SDValue()) {
7167 SDLoc DL(Op);
7168 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
7169
7170 if (IsDouble)
7171 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
7172
7173 // It's a float: cast and extract a vector element.
7174 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
7175 VecConstant);
7176 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
7177 DAG.getConstant(0, DL, MVT::i32));
7178 }
7179
7180 return SDValue();
7181}
7182
7183// check if an VEXT instruction can handle the shuffle mask when the
7184// vector sources of the shuffle are the same.
7185static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
7186 unsigned NumElts = VT.getVectorNumElements();
7187
7188 // Assume that the first shuffle index is not UNDEF. Fail if it is.
7189 if (M[0] < 0)
7190 return false;
7191
7192 Imm = M[0];
7193
7194 // If this is a VEXT shuffle, the immediate value is the index of the first
7195 // element. The other shuffle indices must be the successive elements after
7196 // the first one.
7197 unsigned ExpectedElt = Imm;
7198 for (unsigned i = 1; i < NumElts; ++i) {
7199 // Increment the expected index. If it wraps around, just follow it
7200 // back to index zero and keep going.
7201 ++ExpectedElt;
7202 if (ExpectedElt == NumElts)
7203 ExpectedElt = 0;
7204
7205 if (M[i] < 0) continue; // ignore UNDEF indices
7206 if (ExpectedElt != static_cast<unsigned>(M[i]))
7207 return false;
7208 }
7209
7210 return true;
7211}
7212
7213static bool isVEXTMask(ArrayRef<int> M, EVT VT,
7214 bool &ReverseVEXT, unsigned &Imm) {
7215 unsigned NumElts = VT.getVectorNumElements();
7216 ReverseVEXT = false;
7217
7218 // Assume that the first shuffle index is not UNDEF. Fail if it is.
7219 if (M[0] < 0)
7220 return false;
7221
7222 Imm = M[0];
7223
7224 // If this is a VEXT shuffle, the immediate value is the index of the first
7225 // element. The other shuffle indices must be the successive elements after
7226 // the first one.
7227 unsigned ExpectedElt = Imm;
7228 for (unsigned i = 1; i < NumElts; ++i) {
7229 // Increment the expected index. If it wraps around, it may still be
7230 // a VEXT but the source vectors must be swapped.
7231 ExpectedElt += 1;
7232 if (ExpectedElt == NumElts * 2) {
7233 ExpectedElt = 0;
7234 ReverseVEXT = true;
7235 }
7236
7237 if (M[i] < 0) continue; // ignore UNDEF indices
7238 if (ExpectedElt != static_cast<unsigned>(M[i]))
7239 return false;
7240 }
7241
7242 // Adjust the index value if the source operands will be swapped.
7243 if (ReverseVEXT)
7244 Imm -= NumElts;
7245
7246 return true;
7247}
7248
7249static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
7250 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
7251 // range, then 0 is placed into the resulting vector. So pretty much any mask
7252 // of 8 elements can work here.
7253 return VT == MVT::v8i8 && M.size() == 8;
7254}
7255
7256/// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
7257/// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
7258static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
7259 unsigned &WhichResult,
7260 bool &isV_UNDEF) {
7261 isV_UNDEF = false;
7262 if (isVTRNMask(ShuffleMask, VT, WhichResult))
7263 return ARMISD::VTRN;
7264 if (isVUZPMask(ShuffleMask, VT, WhichResult))
7265 return ARMISD::VUZP;
7266 if (isVZIPMask(ShuffleMask, VT, WhichResult))
7267 return ARMISD::VZIP;
7268
7269 isV_UNDEF = true;
7270 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
7271 return ARMISD::VTRN;
7272 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7273 return ARMISD::VUZP;
7274 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7275 return ARMISD::VZIP;
7276
7277 return 0;
7278}
7279
7280/// \return true if this is a reverse operation on an vector.
7281static bool isReverseMask(ArrayRef<int> M, EVT VT) {
7282 unsigned NumElts = VT.getVectorNumElements();
7283 // Make sure the mask has the right size.
7284 if (NumElts != M.size())
7285 return false;
7286
7287 // Look for <15, ..., 3, -1, 1, 0>.
7288 for (unsigned i = 0; i != NumElts; ++i)
7289 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
7290 return false;
7291
7292 return true;
7293}
7294
7295static bool isTruncMask(ArrayRef<int> M, EVT VT, bool Top, bool SingleSource) {
7296 unsigned NumElts = VT.getVectorNumElements();
7297 // Make sure the mask has the right size.
7298 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7299 return false;
7300
7301 // Half-width truncation patterns (e.g. v4i32 -> v8i16):
7302 // !Top && SingleSource: <0, 2, 4, 6, 0, 2, 4, 6>
7303 // !Top && !SingleSource: <0, 2, 4, 6, 8, 10, 12, 14>
7304 // Top && SingleSource: <1, 3, 5, 7, 1, 3, 5, 7>
7305 // Top && !SingleSource: <1, 3, 5, 7, 9, 11, 13, 15>
7306 int Ofs = Top ? 1 : 0;
7307 int Upper = SingleSource ? 0 : NumElts;
7308 for (int i = 0, e = NumElts / 2; i != e; ++i) {
7309 if (M[i] >= 0 && M[i] != (i * 2) + Ofs)
7310 return false;
7311 if (M[i + e] >= 0 && M[i + e] != (i * 2) + Ofs + Upper)
7312 return false;
7313 }
7314 return true;
7315}
7316
7317static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top, bool SingleSource) {
7318 unsigned NumElts = VT.getVectorNumElements();
7319 // Make sure the mask has the right size.
7320 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7321 return false;
7322
7323 // If Top
7324 // Look for <0, N, 2, N+2, 4, N+4, ..>.
7325 // This inserts Input2 into Input1
7326 // else if not Top
7327 // Look for <0, N+1, 2, N+3, 4, N+5, ..>
7328 // This inserts Input1 into Input2
7329 unsigned Offset = Top ? 0 : 1;
7330 unsigned N = SingleSource ? 0 : NumElts;
7331 for (unsigned i = 0; i < NumElts; i += 2) {
7332 if (M[i] >= 0 && M[i] != (int)i)
7333 return false;
7334 if (M[i + 1] >= 0 && M[i + 1] != (int)(N + i + Offset))
7335 return false;
7336 }
7337
7338 return true;
7339}
7340
7341static bool isVMOVNTruncMask(ArrayRef<int> M, EVT ToVT, bool rev) {
7342 unsigned NumElts = ToVT.getVectorNumElements();
7343 if (NumElts != M.size())
7344 return false;
7345
7346 // Test if the Trunc can be convertible to a VMOVN with this shuffle. We are
7347 // looking for patterns of:
7348 // !rev: 0 N/2 1 N/2+1 2 N/2+2 ...
7349 // rev: N/2 0 N/2+1 1 N/2+2 2 ...
7350
7351 unsigned Off0 = rev ? NumElts / 2 : 0;
7352 unsigned Off1 = rev ? 0 : NumElts / 2;
7353 for (unsigned i = 0; i < NumElts; i += 2) {
7354 if (M[i] >= 0 && M[i] != (int)(Off0 + i / 2))
7355 return false;
7356 if (M[i + 1] >= 0 && M[i + 1] != (int)(Off1 + i / 2))
7357 return false;
7358 }
7359
7360 return true;
7361}
7362
7363// Reconstruct an MVE VCVT from a BuildVector of scalar fptrunc, all extracted
7364// from a pair of inputs. For example:
7365// BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7366// FP_ROUND(EXTRACT_ELT(Y, 0),
7367// FP_ROUND(EXTRACT_ELT(X, 1),
7368// FP_ROUND(EXTRACT_ELT(Y, 1), ...)
7370 const ARMSubtarget *ST) {
7371 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7372 if (!ST->hasMVEFloatOps())
7373 return SDValue();
7374
7375 SDLoc dl(BV);
7376 EVT VT = BV.getValueType();
7377 if (VT != MVT::v8f16)
7378 return SDValue();
7379
7380 // We are looking for a buildvector of fptrunc elements, where all the
7381 // elements are interleavingly extracted from two sources. Check the first two
7382 // items are valid enough and extract some info from them (they are checked
7383 // properly in the loop below).
7384 if (BV.getOperand(0).getOpcode() != ISD::FP_ROUND ||
7387 return SDValue();
7388 if (BV.getOperand(1).getOpcode() != ISD::FP_ROUND ||
7391 return SDValue();
7392 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7393 SDValue Op1 = BV.getOperand(1).getOperand(0).getOperand(0);
7394 if (Op0.getValueType() != MVT::v4f32 || Op1.getValueType() != MVT::v4f32)
7395 return SDValue();
7396
7397 // Check all the values in the BuildVector line up with our expectations.
7398 for (unsigned i = 1; i < 4; i++) {
7399 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7400 return Trunc.getOpcode() == ISD::FP_ROUND &&
7401 Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7402 Trunc.getOperand(0).getOperand(0) == Op &&
7403 Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7404 };
7405 if (!Check(BV.getOperand(i * 2 + 0), Op0, i))
7406 return SDValue();
7407 if (!Check(BV.getOperand(i * 2 + 1), Op1, i))
7408 return SDValue();
7409 }
7410
7411 SDValue N1 = DAG.getNode(ARMISD::VCVTN, dl, VT, DAG.getUNDEF(VT), Op0,
7412 DAG.getConstant(0, dl, MVT::i32));
7413 return DAG.getNode(ARMISD::VCVTN, dl, VT, N1, Op1,
7414 DAG.getConstant(1, dl, MVT::i32));
7415}
7416
7417// Reconstruct an MVE VCVT from a BuildVector of scalar fpext, all extracted
7418// from a single input on alternating lanes. For example:
7419// BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7420// FP_ROUND(EXTRACT_ELT(X, 2),
7421// FP_ROUND(EXTRACT_ELT(X, 4), ...)
7423 const ARMSubtarget *ST) {
7424 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7425 if (!ST->hasMVEFloatOps())
7426 return SDValue();
7427
7428 SDLoc dl(BV);
7429 EVT VT = BV.getValueType();
7430 if (VT != MVT::v4f32)
7431 return SDValue();
7432
7433 // We are looking for a buildvector of fptext elements, where all the
7434 // elements are alternating lanes from a single source. For example <0,2,4,6>
7435 // or <1,3,5,7>. Check the first two items are valid enough and extract some
7436 // info from them (they are checked properly in the loop below).
7437 if (BV.getOperand(0).getOpcode() != ISD::FP_EXTEND ||
7439 return SDValue();
7440 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7442 if (Op0.getValueType() != MVT::v8f16 || (Offset != 0 && Offset != 1))
7443 return SDValue();
7444
7445 // Check all the values in the BuildVector line up with our expectations.
7446 for (unsigned i = 1; i < 4; i++) {
7447 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7448 return Trunc.getOpcode() == ISD::FP_EXTEND &&
7449 Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7450 Trunc.getOperand(0).getOperand(0) == Op &&
7451 Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7452 };
7453 if (!Check(BV.getOperand(i), Op0, 2 * i + Offset))
7454 return SDValue();
7455 }
7456
7457 return DAG.getNode(ARMISD::VCVTL, dl, VT, Op0,
7458 DAG.getConstant(Offset, dl, MVT::i32));
7459}
7460
7461// If N is an integer constant that can be moved into a register in one
7462// instruction, return an SDValue of such a constant (will become a MOV
7463// instruction). Otherwise return null.
7465 const ARMSubtarget *ST, const SDLoc &dl) {
7466 uint64_t Val;
7467 if (!isa<ConstantSDNode>(N))
7468 return SDValue();
7469 Val = N->getAsZExtVal();
7470
7471 if (ST->isThumb1Only()) {
7472 if (Val <= 255 || ~Val <= 255)
7473 return DAG.getConstant(Val, dl, MVT::i32);
7474 } else {
7475 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
7476 return DAG.getConstant(Val, dl, MVT::i32);
7477 }
7478 return SDValue();
7479}
7480
7482 const ARMSubtarget *ST) {
7483 SDLoc dl(Op);
7484 EVT VT = Op.getValueType();
7485
7486 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
7487
7488 unsigned NumElts = VT.getVectorNumElements();
7489 unsigned BoolMask;
7490 unsigned BitsPerBool;
7491 if (NumElts == 2) {
7492 BitsPerBool = 8;
7493 BoolMask = 0xff;
7494 } else if (NumElts == 4) {
7495 BitsPerBool = 4;
7496 BoolMask = 0xf;
7497 } else if (NumElts == 8) {
7498 BitsPerBool = 2;
7499 BoolMask = 0x3;
7500 } else if (NumElts == 16) {
7501 BitsPerBool = 1;
7502 BoolMask = 0x1;
7503 } else
7504 return SDValue();
7505
7506 // If this is a single value copied into all lanes (a splat), we can just sign
7507 // extend that single value
7508 SDValue FirstOp = Op.getOperand(0);
7509 if (!isa<ConstantSDNode>(FirstOp) &&
7510 llvm::all_of(llvm::drop_begin(Op->ops()), [&FirstOp](const SDUse &U) {
7511 return U.get().isUndef() || U.get() == FirstOp;
7512 })) {
7513 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp,
7514 DAG.getValueType(MVT::i1));
7515 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext);
7516 }
7517
7518 // First create base with bits set where known
7519 unsigned Bits32 = 0;
7520 for (unsigned i = 0; i < NumElts; ++i) {
7521 SDValue V = Op.getOperand(i);
7522 if (!isa<ConstantSDNode>(V) && !V.isUndef())
7523 continue;
7524 bool BitSet = V.isUndef() ? false : V->getAsZExtVal();
7525 if (BitSet)
7526 Bits32 |= BoolMask << (i * BitsPerBool);
7527 }
7528
7529 // Add in unknown nodes
7530 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
7531 DAG.getConstant(Bits32, dl, MVT::i32));
7532 for (unsigned i = 0; i < NumElts; ++i) {
7533 SDValue V = Op.getOperand(i);
7534 if (isa<ConstantSDNode>(V) || V.isUndef())
7535 continue;
7536 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
7537 DAG.getConstant(i, dl, MVT::i32));
7538 }
7539
7540 return Base;
7541}
7542
7544 const ARMSubtarget *ST) {
7545 if (!ST->hasMVEIntegerOps())
7546 return SDValue();
7547
7548 // We are looking for a buildvector where each element is Op[0] + i*N
7549 EVT VT = Op.getValueType();
7550 SDValue Op0 = Op.getOperand(0);
7551 unsigned NumElts = VT.getVectorNumElements();
7552
7553 // Get the increment value from operand 1
7554 SDValue Op1 = Op.getOperand(1);
7555 if (Op1.getOpcode() != ISD::ADD || Op1.getOperand(0) != Op0 ||
7557 return SDValue();
7558 unsigned N = Op1.getConstantOperandVal(1);
7559 if (N != 1 && N != 2 && N != 4 && N != 8)
7560 return SDValue();
7561
7562 // Check that each other operand matches
7563 for (unsigned I = 2; I < NumElts; I++) {
7564 SDValue OpI = Op.getOperand(I);
7565 if (OpI.getOpcode() != ISD::ADD || OpI.getOperand(0) != Op0 ||
7567 OpI.getConstantOperandVal(1) != I * N)
7568 return SDValue();
7569 }
7570
7571 SDLoc DL(Op);
7572 return DAG.getNode(ARMISD::VIDUP, DL, DAG.getVTList(VT, MVT::i32), Op0,
7573 DAG.getConstant(N, DL, MVT::i32));
7574}
7575
7576// Returns true if the operation N can be treated as qr instruction variant at
7577// operand Op.
7578static bool IsQRMVEInstruction(const SDNode *N, const SDNode *Op) {
7579 switch (N->getOpcode()) {
7580 case ISD::ADD:
7581 case ISD::MUL:
7582 case ISD::SADDSAT:
7583 case ISD::UADDSAT:
7584 case ISD::AVGFLOORS:
7585 case ISD::AVGFLOORU:
7586 return true;
7587 case ISD::SUB:
7588 case ISD::SSUBSAT:
7589 case ISD::USUBSAT:
7590 return N->getOperand(1).getNode() == Op;
7592 switch (N->getConstantOperandVal(0)) {
7593 case Intrinsic::arm_mve_add_predicated:
7594 case Intrinsic::arm_mve_mul_predicated:
7595 case Intrinsic::arm_mve_qadd_predicated:
7596 case Intrinsic::arm_mve_vhadd:
7597 case Intrinsic::arm_mve_hadd_predicated:
7598 case Intrinsic::arm_mve_vqdmulh:
7599 case Intrinsic::arm_mve_qdmulh_predicated:
7600 case Intrinsic::arm_mve_vqrdmulh:
7601 case Intrinsic::arm_mve_qrdmulh_predicated:
7602 case Intrinsic::arm_mve_vqdmull:
7603 case Intrinsic::arm_mve_vqdmull_predicated:
7604 return true;
7605 case Intrinsic::arm_mve_sub_predicated:
7606 case Intrinsic::arm_mve_qsub_predicated:
7607 case Intrinsic::arm_mve_vhsub:
7608 case Intrinsic::arm_mve_hsub_predicated:
7609 return N->getOperand(2).getNode() == Op;
7610 default:
7611 return false;
7612 }
7613 default:
7614 return false;
7615 }
7616}
7617
7618// If this is a case we can't handle, return null and let the default
7619// expansion code take care of it.
7620SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
7621 const ARMSubtarget *ST) const {
7622 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7623 SDLoc dl(Op);
7624 EVT VT = Op.getValueType();
7625
7626 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7627 return LowerBUILD_VECTOR_i1(Op, DAG, ST);
7628
7629 if (SDValue R = LowerBUILD_VECTORToVIDUP(Op, DAG, ST))
7630 return R;
7631
7632 APInt SplatBits, SplatUndef;
7633 unsigned SplatBitSize;
7634 bool HasAnyUndefs;
7635 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7636 if (SplatUndef.isAllOnes())
7637 return DAG.getUNDEF(VT);
7638
7639 // If all the users of this constant splat are qr instruction variants,
7640 // generate a vdup of the constant.
7641 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == SplatBitSize &&
7642 (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32) &&
7643 all_of(BVN->users(),
7644 [BVN](const SDNode *U) { return IsQRMVEInstruction(U, BVN); })) {
7645 EVT DupVT = SplatBitSize == 32 ? MVT::v4i32
7646 : SplatBitSize == 16 ? MVT::v8i16
7647 : MVT::v16i8;
7648 SDValue Const = DAG.getConstant(SplatBits.getZExtValue(), dl, MVT::i32);
7649 SDValue VDup = DAG.getNode(ARMISD::VDUP, dl, DupVT, Const);
7650 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, VDup);
7651 }
7652
7653 if ((ST->hasNEON() && SplatBitSize <= 64) ||
7654 (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) {
7655 // Check if an immediate VMOV works.
7656 EVT VmovVT;
7657 SDValue Val =
7658 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
7659 SplatBitSize, DAG, dl, VmovVT, VT, VMOVModImm);
7660
7661 if (Val.getNode()) {
7662 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
7663 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Vmov);
7664 }
7665
7666 // Try an immediate VMVN.
7667 uint64_t NegatedImm = (~SplatBits).getZExtValue();
7668 Val = isVMOVModifiedImm(
7669 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VmovVT,
7670 VT, ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
7671 if (Val.getNode()) {
7672 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
7673 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Vmov);
7674 }
7675
7676 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7677 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7678 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
7679 if (ImmVal != -1) {
7680 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
7681 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
7682 }
7683 }
7684
7685 // If we are under MVE, generate a VDUP(constant), bitcast to the original
7686 // type.
7687 if (ST->hasMVEIntegerOps() &&
7688 (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32)) {
7689 EVT DupVT = SplatBitSize == 32 ? MVT::v4i32
7690 : SplatBitSize == 16 ? MVT::v8i16
7691 : MVT::v16i8;
7692 SDValue Const = DAG.getConstant(SplatBits.getZExtValue(), dl, MVT::i32);
7693 SDValue VDup = DAG.getNode(ARMISD::VDUP, dl, DupVT, Const);
7694 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, VDup);
7695 }
7696 }
7697 }
7698
7699 // Scan through the operands to see if only one value is used.
7700 //
7701 // As an optimisation, even if more than one value is used it may be more
7702 // profitable to splat with one value then change some lanes.
7703 //
7704 // Heuristically we decide to do this if the vector has a "dominant" value,
7705 // defined as splatted to more than half of the lanes.
7706 unsigned NumElts = VT.getVectorNumElements();
7707 bool isOnlyLowElement = true;
7708 bool usesOnlyOneValue = true;
7709 bool hasDominantValue = false;
7710 bool isConstant = true;
7711
7712 // Map of the number of times a particular SDValue appears in the
7713 // element list.
7714 DenseMap<SDValue, unsigned> ValueCounts;
7715 SDValue Value;
7716 for (unsigned i = 0; i < NumElts; ++i) {
7717 SDValue V = Op.getOperand(i);
7718 if (V.isUndef())
7719 continue;
7720 if (i > 0)
7721 isOnlyLowElement = false;
7723 isConstant = false;
7724
7725 unsigned &Count = ValueCounts[V];
7726
7727 // Is this value dominant? (takes up more than half of the lanes)
7728 if (++Count > (NumElts / 2)) {
7729 hasDominantValue = true;
7730 Value = V;
7731 }
7732 }
7733 if (ValueCounts.size() != 1)
7734 usesOnlyOneValue = false;
7735 if (!Value.getNode() && !ValueCounts.empty())
7736 Value = ValueCounts.begin()->first;
7737
7738 if (ValueCounts.empty())
7739 return DAG.getUNDEF(VT);
7740
7741 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7742 // Keep going if we are hitting this case.
7743 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()) &&
7744 (VT != MVT::v8f16 || ST->hasFullFP16()))
7745 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7746
7747 unsigned EltSize = VT.getScalarSizeInBits();
7748
7749 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
7750 // i32 and try again.
7751 if (hasDominantValue && EltSize <= 32) {
7752 if (!isConstant) {
7753 SDValue N;
7754
7755 // If we are VDUPing a value that comes directly from a vector, that will
7756 // cause an unnecessary move to and from a GPR, where instead we could
7757 // just use VDUPLANE. We can only do this if the lane being extracted
7758 // is at a constant index, as the VDUP from lane instructions only have
7759 // constant-index forms.
7760 ConstantSDNode *constIndex;
7761 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7762 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
7763 // We need to create a new undef vector to use for the VDUPLANE if the
7764 // size of the vector from which we get the value is different than the
7765 // size of the vector that we need to create. We will insert the element
7766 // such that the register coalescer will remove unnecessary copies.
7767 if (VT != Value->getOperand(0).getValueType()) {
7768 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7770 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7771 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
7772 Value, DAG.getConstant(index, dl, MVT::i32)),
7773 DAG.getConstant(index, dl, MVT::i32));
7774 } else
7775 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7776 Value->getOperand(0), Value->getOperand(1));
7777 } else
7778 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
7779
7780 if (!usesOnlyOneValue) {
7781 // The dominant value was splatted as 'N', but we now have to insert
7782 // all differing elements.
7783 for (unsigned I = 0; I < NumElts; ++I) {
7784 if (Op.getOperand(I) == Value)
7785 continue;
7787 Ops.push_back(N);
7788 Ops.push_back(Op.getOperand(I));
7789 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
7790 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
7791 }
7792 }
7793 return N;
7794 }
7797 MVT FVT = VT.getVectorElementType().getSimpleVT();
7798 assert(FVT == MVT::f32 || FVT == MVT::f16);
7799 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7800 for (unsigned i = 0; i < NumElts; ++i)
7801 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
7802 Op.getOperand(i)));
7803 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
7804 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7805 Val = LowerBUILD_VECTOR(Val, DAG, ST);
7806 if (Val.getNode())
7807 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7808 }
7809 if (usesOnlyOneValue) {
7810 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
7811 if (isConstant && Val.getNode())
7812 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
7813 }
7814 }
7815
7816 // If all elements are constants and the case above didn't get hit, fall back
7817 // to the default expansion, which will generate a load from the constant
7818 // pool.
7819 if (isConstant)
7820 return SDValue();
7821
7822 // Reconstruct the BUILDVECTOR to one of the legal shuffles (such as vext and
7823 // vmovn). Empirical tests suggest this is rarely worth it for vectors of
7824 // length <= 2.
7825 if (NumElts >= 4)
7826 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
7827 return shuffle;
7828
7829 // Attempt to turn a buildvector of scalar fptrunc's or fpext's back into
7830 // VCVT's
7831 if (SDValue VCVT = LowerBuildVectorOfFPTrunc(Op, DAG, Subtarget))
7832 return VCVT;
7833 if (SDValue VCVT = LowerBuildVectorOfFPExt(Op, DAG, Subtarget))
7834 return VCVT;
7835
7836 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7837 // If we haven't found an efficient lowering, try splitting a 128-bit vector
7838 // into two 64-bit vectors; we might discover a better way to lower it.
7839 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7840 EVT ExtVT = VT.getVectorElementType();
7841 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
7842 SDValue Lower = DAG.getBuildVector(HVT, dl, ArrayRef(&Ops[0], NumElts / 2));
7843 if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7844 Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
7845 SDValue Upper =
7846 DAG.getBuildVector(HVT, dl, ArrayRef(&Ops[NumElts / 2], NumElts / 2));
7847 if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7848 Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
7849 if (Lower && Upper)
7850 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
7851 }
7852
7853 // Vectors with 32- or 64-bit elements can be built by directly assigning
7854 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
7855 // will be legalized.
7856 if (EltSize >= 32) {
7857 // Do the expansion with floating-point types, since that is what the VFP
7858 // registers are defined to use, and since i64 is not legal.
7859 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7860 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7862 for (unsigned i = 0; i < NumElts; ++i)
7863 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
7864 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7865 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7866 }
7867
7868 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7869 // know the default expansion would otherwise fall back on something even
7870 // worse. For a vector with one or two non-undef values, that's
7871 // scalar_to_vector for the elements followed by a shuffle (provided the
7872 // shuffle is valid for the target) and materialization element by element
7873 // on the stack followed by a load for everything else.
7874 if ((!isConstant && !usesOnlyOneValue) ||
7875 (VT == MVT::v8f16 && !ST->hasFullFP16())) {
7876 SDValue Vec = DAG.getUNDEF(VT);
7877 for (unsigned i = 0 ; i < NumElts; ++i) {
7878 SDValue V = Op.getOperand(i);
7879 if (V.isUndef())
7880 continue;
7881 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
7882 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7883 }
7884 return Vec;
7885 }
7886
7887 return SDValue();
7888}
7889
7890// Gather data to see if the operation can be modelled as a
7891// shuffle in combination with VEXTs.
7892SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7893 SelectionDAG &DAG) const {
7894 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7895 SDLoc dl(Op);
7896 EVT VT = Op.getValueType();
7897 unsigned NumElts = VT.getVectorNumElements();
7898
7899 struct ShuffleSourceInfo {
7900 SDValue Vec;
7901 unsigned MinElt = std::numeric_limits<unsigned>::max();
7902 unsigned MaxElt = 0;
7903
7904 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7905 // be compatible with the shuffle we intend to construct. As a result
7906 // ShuffleVec will be some sliding window into the original Vec.
7907 SDValue ShuffleVec;
7908
7909 // Code should guarantee that element i in Vec starts at element "WindowBase
7910 // + i * WindowScale in ShuffleVec".
7911 int WindowBase = 0;
7912 int WindowScale = 1;
7913
7914 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7915
7916 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7917 };
7918
7919 // First gather all vectors used as an immediate source for this BUILD_VECTOR
7920 // node.
7922 for (unsigned i = 0; i < NumElts; ++i) {
7923 SDValue V = Op.getOperand(i);
7924 if (V.isUndef())
7925 continue;
7926 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7927 // A shuffle can only come from building a vector from various
7928 // elements of other vectors.
7929 return SDValue();
7930 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
7931 // Furthermore, shuffles require a constant mask, whereas extractelts
7932 // accept variable indices.
7933 return SDValue();
7934 }
7935
7936 // Add this element source to the list if it's not already there.
7937 SDValue SourceVec = V.getOperand(0);
7938 auto Source = llvm::find(Sources, SourceVec);
7939 if (Source == Sources.end())
7940 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7941
7942 // Update the minimum and maximum lane number seen.
7943 unsigned EltNo = V.getConstantOperandVal(1);
7944 Source->MinElt = std::min(Source->MinElt, EltNo);
7945 Source->MaxElt = std::max(Source->MaxElt, EltNo);
7946 }
7947
7948 // Currently only do something sane when at most two source vectors
7949 // are involved.
7950 if (Sources.size() > 2)
7951 return SDValue();
7952
7953 // Find out the smallest element size among result and two sources, and use
7954 // it as element size to build the shuffle_vector.
7955 EVT SmallestEltTy = VT.getVectorElementType();
7956 for (auto &Source : Sources) {
7957 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7958 if (SrcEltTy.bitsLT(SmallestEltTy))
7959 SmallestEltTy = SrcEltTy;
7960 }
7961 unsigned ResMultiplier =
7962 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7963 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7964 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7965
7966 // If the source vector is too wide or too narrow, we may nevertheless be able
7967 // to construct a compatible shuffle either by concatenating it with UNDEF or
7968 // extracting a suitable range of elements.
7969 for (auto &Src : Sources) {
7970 EVT SrcVT = Src.ShuffleVec.getValueType();
7971
7972 uint64_t SrcVTSize = SrcVT.getFixedSizeInBits();
7973 uint64_t VTSize = VT.getFixedSizeInBits();
7974 if (SrcVTSize == VTSize)
7975 continue;
7976
7977 // This stage of the search produces a source with the same element type as
7978 // the original, but with a total width matching the BUILD_VECTOR output.
7979 EVT EltVT = SrcVT.getVectorElementType();
7980 unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits();
7981 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7982
7983 if (SrcVTSize < VTSize) {
7984 if (2 * SrcVTSize != VTSize)
7985 return SDValue();
7986 // We can pad out the smaller vector for free, so if it's part of a
7987 // shuffle...
7988 Src.ShuffleVec =
7989 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7990 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7991 continue;
7992 }
7993
7994 if (SrcVTSize != 2 * VTSize)
7995 return SDValue();
7996
7997 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7998 // Span too large for a VEXT to cope
7999 return SDValue();
8000 }
8001
8002 if (Src.MinElt >= NumSrcElts) {
8003 // The extraction can just take the second half
8004 Src.ShuffleVec =
8005 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8006 DAG.getConstant(NumSrcElts, dl, MVT::i32));
8007 Src.WindowBase = -NumSrcElts;
8008 } else if (Src.MaxElt < NumSrcElts) {
8009 // The extraction can just take the first half
8010 Src.ShuffleVec =
8011 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8012 DAG.getConstant(0, dl, MVT::i32));
8013 } else {
8014 // An actual VEXT is needed
8015 SDValue VEXTSrc1 =
8016 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8017 DAG.getConstant(0, dl, MVT::i32));
8018 SDValue VEXTSrc2 =
8019 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8020 DAG.getConstant(NumSrcElts, dl, MVT::i32));
8021
8022 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
8023 VEXTSrc2,
8024 DAG.getConstant(Src.MinElt, dl, MVT::i32));
8025 Src.WindowBase = -Src.MinElt;
8026 }
8027 }
8028
8029 // Another possible incompatibility occurs from the vector element types. We
8030 // can fix this by bitcasting the source vectors to the same type we intend
8031 // for the shuffle.
8032 for (auto &Src : Sources) {
8033 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
8034 if (SrcEltTy == SmallestEltTy)
8035 continue;
8036 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
8037 Src.ShuffleVec = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, ShuffleVT, Src.ShuffleVec);
8038 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
8039 Src.WindowBase *= Src.WindowScale;
8040 }
8041
8042 // Final check before we try to actually produce a shuffle.
8043 LLVM_DEBUG({
8044 for (auto Src : Sources)
8045 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
8046 });
8047
8048 // The stars all align, our next step is to produce the mask for the shuffle.
8049 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
8050 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
8051 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
8052 SDValue Entry = Op.getOperand(i);
8053 if (Entry.isUndef())
8054 continue;
8055
8056 auto Src = llvm::find(Sources, Entry.getOperand(0));
8057 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
8058
8059 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
8060 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
8061 // segment.
8062 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
8063 int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(),
8064 VT.getScalarSizeInBits());
8065 int LanesDefined = BitsDefined / BitsPerShuffleLane;
8066
8067 // This source is expected to fill ResMultiplier lanes of the final shuffle,
8068 // starting at the appropriate offset.
8069 int *LaneMask = &Mask[i * ResMultiplier];
8070
8071 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
8072 ExtractBase += NumElts * (Src - Sources.begin());
8073 for (int j = 0; j < LanesDefined; ++j)
8074 LaneMask[j] = ExtractBase + j;
8075 }
8076
8077
8078 // We can't handle more than two sources. This should have already
8079 // been checked before this point.
8080 assert(Sources.size() <= 2 && "Too many sources!");
8081
8082 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
8083 for (unsigned i = 0; i < Sources.size(); ++i)
8084 ShuffleOps[i] = Sources[i].ShuffleVec;
8085
8086 SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
8087 ShuffleOps[1], Mask, DAG);
8088 if (!Shuffle)
8089 return SDValue();
8090 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuffle);
8091}
8092
8094 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8103 OP_VUZPL, // VUZP, left result
8104 OP_VUZPR, // VUZP, right result
8105 OP_VZIPL, // VZIP, left result
8106 OP_VZIPR, // VZIP, right result
8107 OP_VTRNL, // VTRN, left result
8108 OP_VTRNR // VTRN, right result
8109};
8110
8111static bool isLegalMVEShuffleOp(unsigned PFEntry) {
8112 unsigned OpNum = (PFEntry >> 26) & 0x0F;
8113 switch (OpNum) {
8114 case OP_COPY:
8115 case OP_VREV:
8116 case OP_VDUP0:
8117 case OP_VDUP1:
8118 case OP_VDUP2:
8119 case OP_VDUP3:
8120 return true;
8121 }
8122 return false;
8123}
8124
8125/// isShuffleMaskLegal - Targets can use this to indicate that they only
8126/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
8127/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
8128/// are assumed to be legal.
8130 if (VT.getVectorNumElements() == 4 &&
8131 (VT.is128BitVector() || VT.is64BitVector())) {
8132 unsigned PFIndexes[4];
8133 for (unsigned i = 0; i != 4; ++i) {
8134 if (M[i] < 0)
8135 PFIndexes[i] = 8;
8136 else
8137 PFIndexes[i] = M[i];
8138 }
8139
8140 // Compute the index in the perfect shuffle table.
8141 unsigned PFTableIndex =
8142 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8143 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8144 unsigned Cost = (PFEntry >> 30);
8145
8146 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
8147 return true;
8148 }
8149
8150 bool ReverseVEXT, isV_UNDEF;
8151 unsigned Imm, WhichResult;
8152
8153 unsigned EltSize = VT.getScalarSizeInBits();
8154 if (EltSize >= 32 ||
8156 ShuffleVectorInst::isIdentityMask(M, M.size()) ||
8157 isVREVMask(M, VT, 64) ||
8158 isVREVMask(M, VT, 32) ||
8159 isVREVMask(M, VT, 16))
8160 return true;
8161 else if (Subtarget->hasNEON() &&
8162 (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
8163 isVTBLMask(M, VT) ||
8164 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
8165 return true;
8166 else if ((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8167 isReverseMask(M, VT))
8168 return true;
8169 else if (Subtarget->hasMVEIntegerOps() &&
8170 (isVMOVNMask(M, VT, true, false) ||
8171 isVMOVNMask(M, VT, false, false) || isVMOVNMask(M, VT, true, true)))
8172 return true;
8173 else if (Subtarget->hasMVEIntegerOps() &&
8174 (isTruncMask(M, VT, false, false) ||
8175 isTruncMask(M, VT, false, true) ||
8176 isTruncMask(M, VT, true, false) || isTruncMask(M, VT, true, true)))
8177 return true;
8178 else
8179 return false;
8180}
8181
8182/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8183/// the specified operations to build the shuffle.
8185 SDValue RHS, SelectionDAG &DAG,
8186 const SDLoc &dl) {
8187 unsigned OpNum = (PFEntry >> 26) & 0x0F;
8188 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8189 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
8190
8191 if (OpNum == OP_COPY) {
8192 if (LHSID == (1*9+2)*9+3) return LHS;
8193 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
8194 return RHS;
8195 }
8196
8197 SDValue OpLHS, OpRHS;
8198 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8199 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8200 EVT VT = OpLHS.getValueType();
8201
8202 switch (OpNum) {
8203 default: llvm_unreachable("Unknown shuffle opcode!");
8204 case OP_VREV:
8205 // VREV divides the vector in half and swaps within the half.
8206 if (VT.getScalarSizeInBits() == 32)
8207 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
8208 // vrev <4 x i16> -> VREV32
8209 if (VT.getScalarSizeInBits() == 16)
8210 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
8211 // vrev <4 x i8> -> VREV16
8212 assert(VT.getScalarSizeInBits() == 8);
8213 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
8214 case OP_VDUP0:
8215 case OP_VDUP1:
8216 case OP_VDUP2:
8217 case OP_VDUP3:
8218 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
8219 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
8220 case OP_VEXT1:
8221 case OP_VEXT2:
8222 case OP_VEXT3:
8223 return DAG.getNode(ARMISD::VEXT, dl, VT,
8224 OpLHS, OpRHS,
8225 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
8226 case OP_VUZPL:
8227 case OP_VUZPR:
8228 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
8229 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
8230 case OP_VZIPL:
8231 case OP_VZIPR:
8232 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
8233 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
8234 case OP_VTRNL:
8235 case OP_VTRNR:
8236 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
8237 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
8238 }
8239}
8240
8242 ArrayRef<int> ShuffleMask,
8243 SelectionDAG &DAG) {
8244 // Check to see if we can use the VTBL instruction.
8245 SDValue V1 = Op.getOperand(0);
8246 SDValue V2 = Op.getOperand(1);
8247 SDLoc DL(Op);
8248
8249 SmallVector<SDValue, 8> VTBLMask;
8250 for (int I : ShuffleMask)
8251 VTBLMask.push_back(DAG.getSignedConstant(I, DL, MVT::i32));
8252
8253 if (V2.getNode()->isUndef())
8254 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
8255 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8256
8257 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
8258 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8259}
8260
8262 SDLoc DL(Op);
8263 EVT VT = Op.getValueType();
8264
8265 assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8266 "Expect an v8i16/v16i8 type");
8267 SDValue OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, Op.getOperand(0));
8268 // For a v16i8 type: After the VREV, we have got <7, ..., 0, 15, ..., 8>. Now,
8269 // extract the first 8 bytes into the top double word and the last 8 bytes
8270 // into the bottom double word, through a new vector shuffle that will be
8271 // turned into a VEXT on Neon, or a couple of VMOVDs on MVE.
8272 std::vector<int> NewMask;
8273 for (unsigned i = 0; i < VT.getVectorNumElements() / 2; i++)
8274 NewMask.push_back(VT.getVectorNumElements() / 2 + i);
8275 for (unsigned i = 0; i < VT.getVectorNumElements() / 2; i++)
8276 NewMask.push_back(i);
8277 return DAG.getVectorShuffle(VT, DL, OpLHS, OpLHS, NewMask);
8278}
8279
8281 switch (VT.getSimpleVT().SimpleTy) {
8282 case MVT::v2i1:
8283 return MVT::v2f64;
8284 case MVT::v4i1:
8285 return MVT::v4i32;
8286 case MVT::v8i1:
8287 return MVT::v8i16;
8288 case MVT::v16i1:
8289 return MVT::v16i8;
8290 default:
8291 llvm_unreachable("Unexpected vector predicate type");
8292 }
8293}
8294
8296 SelectionDAG &DAG) {
8297 // Converting from boolean predicates to integers involves creating a vector
8298 // of all ones or all zeroes and selecting the lanes based upon the real
8299 // predicate.
8301 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
8302 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
8303
8304 SDValue AllZeroes =
8305 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
8306 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
8307
8308 // Get full vector type from predicate type
8310
8311 SDValue RecastV1;
8312 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
8313 // this to a v16i1. This cannot be done with an ordinary bitcast because the
8314 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
8315 // since we know in hardware the sizes are really the same.
8316 if (VT != MVT::v16i1)
8317 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
8318 else
8319 RecastV1 = Pred;
8320
8321 // Select either all ones or zeroes depending upon the real predicate bits.
8322 SDValue PredAsVector =
8323 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
8324
8325 // Recast our new predicate-as-integer v16i8 vector into something
8326 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
8327 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
8328}
8329
8331 const ARMSubtarget *ST) {
8332 EVT VT = Op.getValueType();
8334 ArrayRef<int> ShuffleMask = SVN->getMask();
8335
8336 assert(ST->hasMVEIntegerOps() &&
8337 "No support for vector shuffle of boolean predicates");
8338
8339 SDValue V1 = Op.getOperand(0);
8340 SDValue V2 = Op.getOperand(1);
8341 SDLoc dl(Op);
8342 if (isReverseMask(ShuffleMask, VT)) {
8343 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
8344 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
8345 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
8346 DAG.getConstant(16, dl, MVT::i32));
8347 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
8348 }
8349
8350 // Until we can come up with optimised cases for every single vector
8351 // shuffle in existence we have chosen the least painful strategy. This is
8352 // to essentially promote the boolean predicate to a 8-bit integer, where
8353 // each predicate represents a byte. Then we fall back on a normal integer
8354 // vector shuffle and convert the result back into a predicate vector. In
8355 // many cases the generated code might be even better than scalar code
8356 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
8357 // fields in a register into 8 other arbitrary 2-bit fields!
8358 SDValue PredAsVector1 = PromoteMVEPredVector(dl, V1, VT, DAG);
8359 EVT NewVT = PredAsVector1.getValueType();
8360 SDValue PredAsVector2 = V2.isUndef() ? DAG.getUNDEF(NewVT)
8361 : PromoteMVEPredVector(dl, V2, VT, DAG);
8362 assert(PredAsVector2.getValueType() == NewVT &&
8363 "Expected identical vector type in expanded i1 shuffle!");
8364
8365 // Do the shuffle!
8366 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector1,
8367 PredAsVector2, ShuffleMask);
8368
8369 // Now return the result of comparing the shuffled vector with zero,
8370 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. For a v2i1
8371 // we convert to a v4i1 compare to fill in the two halves of the i64 as i32s.
8372 if (VT == MVT::v2i1) {
8373 SDValue BC = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Shuffled);
8374 SDValue Cmp = DAG.getNode(ARMISD::VCMPZ, dl, MVT::v4i1, BC,
8375 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8376 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v2i1, Cmp);
8377 }
8378 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
8379 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8380}
8381
8383 ArrayRef<int> ShuffleMask,
8384 SelectionDAG &DAG) {
8385 // Attempt to lower the vector shuffle using as many whole register movs as
8386 // possible. This is useful for types smaller than 32bits, which would
8387 // often otherwise become a series for grp movs.
8388 SDLoc dl(Op);
8389 EVT VT = Op.getValueType();
8390 if (VT.getScalarSizeInBits() >= 32)
8391 return SDValue();
8392
8393 assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8394 "Unexpected vector type");
8395 int NumElts = VT.getVectorNumElements();
8396 int QuarterSize = NumElts / 4;
8397 // The four final parts of the vector, as i32's
8398 SDValue Parts[4];
8399
8400 // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not
8401 // <u,u,u,u>), returning the vmov lane index
8402 auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) {
8403 // Detect which mov lane this would be from the first non-undef element.
8404 int MovIdx = -1;
8405 for (int i = 0; i < Length; i++) {
8406 if (ShuffleMask[Start + i] >= 0) {
8407 if (ShuffleMask[Start + i] % Length != i)
8408 return -1;
8409 MovIdx = ShuffleMask[Start + i] / Length;
8410 break;
8411 }
8412 }
8413 // If all items are undef, leave this for other combines
8414 if (MovIdx == -1)
8415 return -1;
8416 // Check the remaining values are the correct part of the same mov
8417 for (int i = 1; i < Length; i++) {
8418 if (ShuffleMask[Start + i] >= 0 &&
8419 (ShuffleMask[Start + i] / Length != MovIdx ||
8420 ShuffleMask[Start + i] % Length != i))
8421 return -1;
8422 }
8423 return MovIdx;
8424 };
8425
8426 for (int Part = 0; Part < 4; ++Part) {
8427 // Does this part look like a mov
8428 int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize);
8429 if (Elt != -1) {
8430 SDValue Input = Op->getOperand(0);
8431 if (Elt >= 4) {
8432 Input = Op->getOperand(1);
8433 Elt -= 4;
8434 }
8435 SDValue BitCast = DAG.getBitcast(MVT::v4f32, Input);
8436 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, BitCast,
8437 DAG.getConstant(Elt, dl, MVT::i32));
8438 }
8439 }
8440
8441 // Nothing interesting found, just return
8442 if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3])
8443 return SDValue();
8444
8445 // The other parts need to be built with the old shuffle vector, cast to a
8446 // v4i32 and extract_vector_elts
8447 if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) {
8448 SmallVector<int, 16> NewShuffleMask;
8449 for (int Part = 0; Part < 4; ++Part)
8450 for (int i = 0; i < QuarterSize; i++)
8451 NewShuffleMask.push_back(
8452 Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]);
8453 SDValue NewShuffle = DAG.getVectorShuffle(
8454 VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask);
8455 SDValue BitCast = DAG.getBitcast(MVT::v4f32, NewShuffle);
8456
8457 for (int Part = 0; Part < 4; ++Part)
8458 if (!Parts[Part])
8459 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32,
8460 BitCast, DAG.getConstant(Part, dl, MVT::i32));
8461 }
8462 // Build a vector out of the various parts and bitcast it back to the original
8463 // type.
8464 SDValue NewVec = DAG.getNode(ARMISD::BUILD_VECTOR, dl, MVT::v4f32, Parts);
8465 return DAG.getBitcast(VT, NewVec);
8466}
8467
8469 ArrayRef<int> ShuffleMask,
8470 SelectionDAG &DAG) {
8471 SDValue V1 = Op.getOperand(0);
8472 SDValue V2 = Op.getOperand(1);
8473 EVT VT = Op.getValueType();
8474 unsigned NumElts = VT.getVectorNumElements();
8475
8476 // An One-Off Identity mask is one that is mostly an identity mask from as
8477 // single source but contains a single element out-of-place, either from a
8478 // different vector or from another position in the same vector. As opposed to
8479 // lowering this via a ARMISD::BUILD_VECTOR we can generate an extract/insert
8480 // pair directly.
8481 auto isOneOffIdentityMask = [](ArrayRef<int> Mask, EVT VT, int BaseOffset,
8482 int &OffElement) {
8483 OffElement = -1;
8484 int NonUndef = 0;
8485 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
8486 if (Mask[i] == -1)
8487 continue;
8488 NonUndef++;
8489 if (Mask[i] != i + BaseOffset) {
8490 if (OffElement == -1)
8491 OffElement = i;
8492 else
8493 return false;
8494 }
8495 }
8496 return NonUndef > 2 && OffElement != -1;
8497 };
8498 int OffElement;
8499 SDValue VInput;
8500 if (isOneOffIdentityMask(ShuffleMask, VT, 0, OffElement))
8501 VInput = V1;
8502 else if (isOneOffIdentityMask(ShuffleMask, VT, NumElts, OffElement))
8503 VInput = V2;
8504 else
8505 return SDValue();
8506
8507 SDLoc dl(Op);
8508 EVT SVT = VT.getScalarType() == MVT::i8 || VT.getScalarType() == MVT::i16
8509 ? MVT::i32
8510 : VT.getScalarType();
8511 SDValue Elt = DAG.getNode(
8512 ISD::EXTRACT_VECTOR_ELT, dl, SVT,
8513 ShuffleMask[OffElement] < (int)NumElts ? V1 : V2,
8514 DAG.getVectorIdxConstant(ShuffleMask[OffElement] % NumElts, dl));
8515 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, VInput, Elt,
8516 DAG.getVectorIdxConstant(OffElement % NumElts, dl));
8517}
8518
8520 const ARMSubtarget *ST) {
8521 SDValue V1 = Op.getOperand(0);
8522 SDValue V2 = Op.getOperand(1);
8523 SDLoc dl(Op);
8524 EVT VT = Op.getValueType();
8526 unsigned EltSize = VT.getScalarSizeInBits();
8527
8528 if (ST->hasMVEIntegerOps() && EltSize == 1)
8529 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
8530
8531 // Convert shuffles that are directly supported on NEON to target-specific
8532 // DAG nodes, instead of keeping them as shuffles and matching them again
8533 // during code selection. This is more efficient and avoids the possibility
8534 // of inconsistencies between legalization and selection.
8535 // FIXME: floating-point vectors should be canonicalized to integer vectors
8536 // of the same time so that they get CSEd properly.
8537 ArrayRef<int> ShuffleMask = SVN->getMask();
8538
8539 if (EltSize <= 32) {
8540 if (SVN->isSplat()) {
8541 int Lane = SVN->getSplatIndex();
8542 // If this is undef splat, generate it via "just" vdup, if possible.
8543 if (Lane == -1) Lane = 0;
8544
8545 // Test if V1 is a SCALAR_TO_VECTOR.
8546 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8547 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8548 }
8549 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
8550 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
8551 // reaches it).
8552 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
8553 !isa<ConstantSDNode>(V1.getOperand(0))) {
8554 bool IsScalarToVector = true;
8555 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
8556 if (!V1.getOperand(i).isUndef()) {
8557 IsScalarToVector = false;
8558 break;
8559 }
8560 if (IsScalarToVector)
8561 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8562 }
8563 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
8564 DAG.getConstant(Lane, dl, MVT::i32));
8565 }
8566
8567 bool ReverseVEXT = false;
8568 unsigned Imm = 0;
8569 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
8570 if (ReverseVEXT)
8571 std::swap(V1, V2);
8572 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
8573 DAG.getConstant(Imm, dl, MVT::i32));
8574 }
8575
8576 if (isVREVMask(ShuffleMask, VT, 64))
8577 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
8578 if (isVREVMask(ShuffleMask, VT, 32))
8579 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
8580 if (isVREVMask(ShuffleMask, VT, 16))
8581 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
8582
8583 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
8584 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
8585 DAG.getConstant(Imm, dl, MVT::i32));
8586 }
8587
8588 // Check for Neon shuffles that modify both input vectors in place.
8589 // If both results are used, i.e., if there are two shuffles with the same
8590 // source operands and with masks corresponding to both results of one of
8591 // these operations, DAG memoization will ensure that a single node is
8592 // used for both shuffles.
8593 unsigned WhichResult = 0;
8594 bool isV_UNDEF = false;
8595 if (ST->hasNEON()) {
8596 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8597 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
8598 if (isV_UNDEF)
8599 V2 = V1;
8600 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
8601 .getValue(WhichResult);
8602 }
8603 }
8604 if (ST->hasMVEIntegerOps()) {
8605 if (isVMOVNMask(ShuffleMask, VT, false, false))
8606 return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1,
8607 DAG.getConstant(0, dl, MVT::i32));
8608 if (isVMOVNMask(ShuffleMask, VT, true, false))
8609 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2,
8610 DAG.getConstant(1, dl, MVT::i32));
8611 if (isVMOVNMask(ShuffleMask, VT, true, true))
8612 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V1,
8613 DAG.getConstant(1, dl, MVT::i32));
8614 }
8615
8616 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
8617 // shuffles that produce a result larger than their operands with:
8618 // shuffle(concat(v1, undef), concat(v2, undef))
8619 // ->
8620 // shuffle(concat(v1, v2), undef)
8621 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
8622 //
8623 // This is useful in the general case, but there are special cases where
8624 // native shuffles produce larger results: the two-result ops.
8625 //
8626 // Look through the concat when lowering them:
8627 // shuffle(concat(v1, v2), undef)
8628 // ->
8629 // concat(VZIP(v1, v2):0, :1)
8630 //
8631 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
8632 SDValue SubV1 = V1->getOperand(0);
8633 SDValue SubV2 = V1->getOperand(1);
8634 EVT SubVT = SubV1.getValueType();
8635
8636 // We expect these to have been canonicalized to -1.
8637 assert(llvm::all_of(ShuffleMask, [&](int i) {
8638 return i < (int)VT.getVectorNumElements();
8639 }) && "Unexpected shuffle index into UNDEF operand!");
8640
8641 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8642 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
8643 if (isV_UNDEF)
8644 SubV2 = SubV1;
8645 assert((WhichResult == 0) &&
8646 "In-place shuffle of concat can only have one result!");
8647 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
8648 SubV1, SubV2);
8649 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
8650 Res.getValue(1));
8651 }
8652 }
8653 }
8654
8655 if (ST->hasMVEIntegerOps() && EltSize <= 32 &&
8656 (ST->hasFullFP16() || VT != MVT::v8f16)) {
8657 if (SDValue V = LowerVECTOR_SHUFFLEUsingOneOff(Op, ShuffleMask, DAG))
8658 return V;
8659
8660 for (bool Top : {false, true}) {
8661 for (bool SingleSource : {false, true}) {
8662 if (isTruncMask(ShuffleMask, VT, Top, SingleSource)) {
8663 MVT FromSVT = MVT::getIntegerVT(EltSize * 2);
8664 MVT FromVT = MVT::getVectorVT(FromSVT, ShuffleMask.size() / 2);
8665 SDValue Lo = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, FromVT, V1);
8666 SDValue Hi = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, FromVT,
8667 SingleSource ? V1 : V2);
8668 if (Top) {
8669 SDValue Amt = DAG.getConstant(EltSize, dl, FromVT);
8670 Lo = DAG.getNode(ISD::SRL, dl, FromVT, Lo, Amt);
8671 Hi = DAG.getNode(ISD::SRL, dl, FromVT, Hi, Amt);
8672 }
8673 return DAG.getNode(ARMISD::MVETRUNC, dl, VT, Lo, Hi);
8674 }
8675 }
8676 }
8677 }
8678
8679 // If the shuffle is not directly supported and it has 4 elements, use
8680 // the PerfectShuffle-generated table to synthesize it from other shuffles.
8681 unsigned NumElts = VT.getVectorNumElements();
8682 if (NumElts == 4) {
8683 unsigned PFIndexes[4];
8684 for (unsigned i = 0; i != 4; ++i) {
8685 if (ShuffleMask[i] < 0)
8686 PFIndexes[i] = 8;
8687 else
8688 PFIndexes[i] = ShuffleMask[i];
8689 }
8690
8691 // Compute the index in the perfect shuffle table.
8692 unsigned PFTableIndex =
8693 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8694 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8695 unsigned Cost = (PFEntry >> 30);
8696
8697 if (Cost <= 4) {
8698 if (ST->hasNEON())
8699 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8700 else if (isLegalMVEShuffleOp(PFEntry)) {
8701 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8702 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
8703 unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
8704 unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
8705 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
8706 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8707 }
8708 }
8709 }
8710
8711 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
8712 if (EltSize >= 32) {
8713 // Do the expansion with floating-point types, since that is what the VFP
8714 // registers are defined to use, and since i64 is not legal.
8715 EVT EltVT = EVT::getFloatingPointVT(EltSize);
8716 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
8717 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
8718 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
8720 for (unsigned i = 0; i < NumElts; ++i) {
8721 if (ShuffleMask[i] < 0)
8722 Ops.push_back(DAG.getUNDEF(EltVT));
8723 else
8724 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8725 ShuffleMask[i] < (int)NumElts ? V1 : V2,
8726 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
8727 dl, MVT::i32)));
8728 }
8729 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
8730 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8731 }
8732
8733 if ((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8734 isReverseMask(ShuffleMask, VT))
8735 return LowerReverse_VECTOR_SHUFFLE(Op, DAG);
8736
8737 if (ST->hasNEON() && VT == MVT::v8i8)
8738 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
8739 return NewOp;
8740
8741 if (ST->hasMVEIntegerOps())
8742 if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG))
8743 return NewOp;
8744
8745 // Lower v8f16 via v8i16 to avoid invalid f16 nodes.
8746 if (VT == MVT::v8f16 && !ST->hasFullFP16()) {
8747 SDValue BC0 =
8748 DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v8i16, Op.getOperand(0));
8749 SDValue BC1 =
8750 DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v8i16, Op.getOperand(1));
8751 SDValue Shuf = DAG.getVectorShuffle(MVT::v8i16, dl, BC0, BC1, ShuffleMask);
8752 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuf);
8753 }
8754
8755 return SDValue();
8756}
8757
8759 const ARMSubtarget *ST) {
8760 EVT VecVT = Op.getOperand(0).getValueType();
8761 SDLoc dl(Op);
8762
8763 assert(ST->hasMVEIntegerOps() &&
8764 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8765
8766 SDValue Conv =
8767 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8768 unsigned Lane = Op.getConstantOperandVal(2);
8769 unsigned LaneWidth =
8771 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
8772 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
8773 Op.getOperand(1), DAG.getValueType(MVT::i1));
8774 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
8775 DAG.getConstant(~Mask, dl, MVT::i32));
8776 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
8777}
8778
8779SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8780 SelectionDAG &DAG) const {
8781 // INSERT_VECTOR_ELT is legal only for immediate indexes.
8782 SDValue Lane = Op.getOperand(2);
8783 if (!isa<ConstantSDNode>(Lane))
8784 return SDValue();
8785
8786 SDValue Elt = Op.getOperand(1);
8787 EVT EltVT = Elt.getValueType();
8788
8789 if (Subtarget->hasMVEIntegerOps() &&
8790 Op.getValueType().getScalarSizeInBits() == 1)
8791 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
8792
8793 if (getTypeAction(*DAG.getContext(), EltVT) ==
8795 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
8796 // but the type system will try to do that if we don't intervene.
8797 // Reinterpret any such vector-element insertion as one with the
8798 // corresponding integer types.
8799
8800 SDLoc dl(Op);
8801
8802 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
8803 assert(getTypeAction(*DAG.getContext(), IEltVT) !=
8805
8806 SDValue VecIn = Op.getOperand(0);
8807 EVT VecVT = VecIn.getValueType();
8808 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
8809 VecVT.getVectorNumElements());
8810
8811 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
8812 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
8813 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
8814 IVecIn, IElt, Lane);
8815 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
8816 }
8817
8818 return Op;
8819}
8820
8822 const ARMSubtarget *ST) {
8823 EVT VecVT = Op.getOperand(0).getValueType();
8824 SDLoc dl(Op);
8825
8826 assert(ST->hasMVEIntegerOps() &&
8827 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8828
8829 SDValue Conv =
8830 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8831 unsigned Lane = Op.getConstantOperandVal(1);
8832 unsigned LaneWidth =
8834 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
8835 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
8836 return Shift;
8837}
8838
8840 const ARMSubtarget *ST) {
8841 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
8842 SDValue Lane = Op.getOperand(1);
8843 if (!isa<ConstantSDNode>(Lane))
8844 return SDValue();
8845
8846 SDValue Vec = Op.getOperand(0);
8847 EVT VT = Vec.getValueType();
8848
8849 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8850 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
8851
8852 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
8853 SDLoc dl(Op);
8854 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
8855 }
8856
8857 return Op;
8858}
8859
8861 const ARMSubtarget *ST) {
8862 SDLoc dl(Op);
8863 assert(Op.getValueType().getScalarSizeInBits() == 1 &&
8864 "Unexpected custom CONCAT_VECTORS lowering");
8865 assert(isPowerOf2_32(Op.getNumOperands()) &&
8866 "Unexpected custom CONCAT_VECTORS lowering");
8867 assert(ST->hasMVEIntegerOps() &&
8868 "CONCAT_VECTORS lowering only supported for MVE");
8869
8870 auto ConcatPair = [&](SDValue V1, SDValue V2) {
8871 EVT Op1VT = V1.getValueType();
8872 EVT Op2VT = V2.getValueType();
8873 assert(Op1VT == Op2VT && "Operand types don't match!");
8874 assert((Op1VT == MVT::v2i1 || Op1VT == MVT::v4i1 || Op1VT == MVT::v8i1) &&
8875 "Unexpected i1 concat operations!");
8876 EVT VT = Op1VT.getDoubleNumVectorElementsVT(*DAG.getContext());
8877
8878 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8879 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
8880
8881 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
8882 // promoted to v8i16, etc.
8883 MVT ElType =
8885 unsigned NumElts = 2 * Op1VT.getVectorNumElements();
8886
8887 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
8888 if (Op1VT == MVT::v4i1 || Op1VT == MVT::v8i1) {
8889 // Use MVETRUNC to truncate the combined NewV1::NewV2 into the smaller
8890 // ConcatVT.
8891 SDValue ConVec =
8892 DAG.getNode(ARMISD::MVETRUNC, dl, ConcatVT, NewV1, NewV2);
8893 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
8894 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8895 }
8896
8897 // Extract the vector elements from Op1 and Op2 one by one and truncate them
8898 // to be the right size for the destination. For example, if Op1 is v4i1
8899 // then the promoted vector is v4i32. The result of concatenation gives a
8900 // v8i1, which when promoted is v8i16. That means each i32 element from Op1
8901 // needs truncating to i16 and inserting in the result.
8902 auto ExtractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
8903 EVT NewVT = NewV.getValueType();
8904 EVT ConcatVT = ConVec.getValueType();
8905 unsigned ExtScale = 1;
8906 if (NewVT == MVT::v2f64) {
8907 NewV = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, NewV);
8908 ExtScale = 2;
8909 }
8910 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
8911 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
8912 DAG.getIntPtrConstant(i * ExtScale, dl));
8913 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
8914 DAG.getConstant(j, dl, MVT::i32));
8915 }
8916 return ConVec;
8917 };
8918 unsigned j = 0;
8919 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
8920 ConVec = ExtractInto(NewV1, ConVec, j);
8921 ConVec = ExtractInto(NewV2, ConVec, j);
8922
8923 // Now return the result of comparing the subvector with zero, which will
8924 // generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8925 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
8926 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8927 };
8928
8929 // Concat each pair of subvectors and pack into the lower half of the array.
8930 SmallVector<SDValue> ConcatOps(Op->ops());
8931 while (ConcatOps.size() > 1) {
8932 for (unsigned I = 0, E = ConcatOps.size(); I != E; I += 2) {
8933 SDValue V1 = ConcatOps[I];
8934 SDValue V2 = ConcatOps[I + 1];
8935 ConcatOps[I / 2] = ConcatPair(V1, V2);
8936 }
8937 ConcatOps.resize(ConcatOps.size() / 2);
8938 }
8939 return ConcatOps[0];
8940}
8941
8943 const ARMSubtarget *ST) {
8944 EVT VT = Op->getValueType(0);
8945 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8946 return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
8947
8948 // The only time a CONCAT_VECTORS operation can have legal types is when
8949 // two 64-bit vectors are concatenated to a 128-bit vector.
8950 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
8951 "unexpected CONCAT_VECTORS");
8952 SDLoc dl(Op);
8953 SDValue Val = DAG.getUNDEF(MVT::v2f64);
8954 SDValue Op0 = Op.getOperand(0);
8955 SDValue Op1 = Op.getOperand(1);
8956 if (!Op0.isUndef())
8957 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8958 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
8959 DAG.getIntPtrConstant(0, dl));
8960 if (!Op1.isUndef())
8961 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8962 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
8963 DAG.getIntPtrConstant(1, dl));
8964 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
8965}
8966
8968 const ARMSubtarget *ST) {
8969 SDValue V1 = Op.getOperand(0);
8970 SDValue V2 = Op.getOperand(1);
8971 SDLoc dl(Op);
8972 EVT VT = Op.getValueType();
8973 EVT Op1VT = V1.getValueType();
8974 unsigned NumElts = VT.getVectorNumElements();
8975 unsigned Index = V2->getAsZExtVal();
8976
8977 assert(VT.getScalarSizeInBits() == 1 &&
8978 "Unexpected custom EXTRACT_SUBVECTOR lowering");
8979 assert(ST->hasMVEIntegerOps() &&
8980 "EXTRACT_SUBVECTOR lowering only supported for MVE");
8981
8982 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8983
8984 // We now have Op1 promoted to a vector of integers, where v8i1 gets
8985 // promoted to v8i16, etc.
8986
8988
8989 if (NumElts == 2) {
8990 EVT SubVT = MVT::v4i32;
8991 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
8992 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j += 2) {
8993 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
8994 DAG.getIntPtrConstant(i, dl));
8995 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
8996 DAG.getConstant(j, dl, MVT::i32));
8997 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
8998 DAG.getConstant(j + 1, dl, MVT::i32));
8999 }
9000 SDValue Cmp = DAG.getNode(ARMISD::VCMPZ, dl, MVT::v4i1, SubVec,
9001 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
9002 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v2i1, Cmp);
9003 }
9004
9005 EVT SubVT = MVT::getVectorVT(ElType, NumElts);
9006 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
9007 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
9008 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
9009 DAG.getIntPtrConstant(i, dl));
9010 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
9011 DAG.getConstant(j, dl, MVT::i32));
9012 }
9013
9014 // Now return the result of comparing the subvector with zero,
9015 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
9016 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
9017 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
9018}
9019
9020// Turn a truncate into a predicate (an i1 vector) into icmp(and(x, 1), 0).
9022 const ARMSubtarget *ST) {
9023 assert(ST->hasMVEIntegerOps() && "Expected MVE!");
9024 EVT VT = N->getValueType(0);
9025 assert((VT == MVT::v16i1 || VT == MVT::v8i1 || VT == MVT::v4i1) &&
9026 "Expected a vector i1 type!");
9027 SDValue Op = N->getOperand(0);
9028 EVT FromVT = Op.getValueType();
9029 SDLoc DL(N);
9030
9031 SDValue And =
9032 DAG.getNode(ISD::AND, DL, FromVT, Op, DAG.getConstant(1, DL, FromVT));
9033 return DAG.getNode(ISD::SETCC, DL, VT, And, DAG.getConstant(0, DL, FromVT),
9034 DAG.getCondCode(ISD::SETNE));
9035}
9036
9038 const ARMSubtarget *Subtarget) {
9039 if (!Subtarget->hasMVEIntegerOps())
9040 return SDValue();
9041
9042 EVT ToVT = N->getValueType(0);
9043 if (ToVT.getScalarType() == MVT::i1)
9044 return LowerTruncatei1(N, DAG, Subtarget);
9045
9046 // MVE does not have a single instruction to perform the truncation of a v4i32
9047 // into the lower half of a v8i16, in the same way that a NEON vmovn would.
9048 // Most of the instructions in MVE follow the 'Beats' system, where moving
9049 // values from different lanes is usually something that the instructions
9050 // avoid.
9051 //
9052 // Instead it has top/bottom instructions such as VMOVLT/B and VMOVNT/B,
9053 // which take a the top/bottom half of a larger lane and extend it (or do the
9054 // opposite, truncating into the top/bottom lane from a larger lane). Note
9055 // that because of the way we widen lanes, a v4i16 is really a v4i32 using the
9056 // bottom 16bits from each vector lane. This works really well with T/B
9057 // instructions, but that doesn't extend to v8i32->v8i16 where the lanes need
9058 // to move order.
9059 //
9060 // But truncates and sext/zext are always going to be fairly common from llvm.
9061 // We have several options for how to deal with them:
9062 // - Wherever possible combine them into an instruction that makes them
9063 // "free". This includes loads/stores, which can perform the trunc as part
9064 // of the memory operation. Or certain shuffles that can be turned into
9065 // VMOVN/VMOVL.
9066 // - Lane Interleaving to transform blocks surrounded by ext/trunc. So
9067 // trunc(mul(sext(a), sext(b))) may become
9068 // VMOVNT(VMUL(VMOVLB(a), VMOVLB(b)), VMUL(VMOVLT(a), VMOVLT(b))). (Which in
9069 // this case can use VMULL). This is performed in the
9070 // MVELaneInterleavingPass.
9071 // - Otherwise we have an option. By default we would expand the
9072 // zext/sext/trunc into a series of lane extract/inserts going via GPR
9073 // registers. One for each vector lane in the vector. This can obviously be
9074 // very expensive.
9075 // - The other option is to use the fact that loads/store can extend/truncate
9076 // to turn a trunc into two truncating stack stores and a stack reload. This
9077 // becomes 3 back-to-back memory operations, but at least that is less than
9078 // all the insert/extracts.
9079 //
9080 // In order to do the last, we convert certain trunc's into MVETRUNC, which
9081 // are either optimized where they can be, or eventually lowered into stack
9082 // stores/loads. This prevents us from splitting a v8i16 trunc into two stores
9083 // two early, where other instructions would be better, and stops us from
9084 // having to reconstruct multiple buildvector shuffles into loads/stores.
9085 if (ToVT != MVT::v8i16 && ToVT != MVT::v16i8)
9086 return SDValue();
9087 EVT FromVT = N->getOperand(0).getValueType();
9088 if (FromVT != MVT::v8i32 && FromVT != MVT::v16i16)
9089 return SDValue();
9090
9091 SDValue Lo, Hi;
9092 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
9093 SDLoc DL(N);
9094 return DAG.getNode(ARMISD::MVETRUNC, DL, ToVT, Lo, Hi);
9095}
9096
9098 const ARMSubtarget *Subtarget) {
9099 if (!Subtarget->hasMVEIntegerOps())
9100 return SDValue();
9101
9102 // See LowerTruncate above for an explanation of MVEEXT/MVETRUNC.
9103
9104 EVT ToVT = N->getValueType(0);
9105 if (ToVT != MVT::v16i32 && ToVT != MVT::v8i32 && ToVT != MVT::v16i16)
9106 return SDValue();
9107 SDValue Op = N->getOperand(0);
9108 EVT FromVT = Op.getValueType();
9109 if (FromVT != MVT::v8i16 && FromVT != MVT::v16i8)
9110 return SDValue();
9111
9112 SDLoc DL(N);
9113 EVT ExtVT = ToVT.getHalfNumVectorElementsVT(*DAG.getContext());
9114 if (ToVT.getScalarType() == MVT::i32 && FromVT.getScalarType() == MVT::i8)
9115 ExtVT = MVT::v8i16;
9116
9117 unsigned Opcode =
9119 SDValue Ext = DAG.getNode(Opcode, DL, DAG.getVTList(ExtVT, ExtVT), Op);
9120 SDValue Ext1 = Ext.getValue(1);
9121
9122 if (ToVT.getScalarType() == MVT::i32 && FromVT.getScalarType() == MVT::i8) {
9123 Ext = DAG.getNode(N->getOpcode(), DL, MVT::v8i32, Ext);
9124 Ext1 = DAG.getNode(N->getOpcode(), DL, MVT::v8i32, Ext1);
9125 }
9126
9127 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Ext, Ext1);
9128}
9129
9130/// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
9131/// element has been zero/sign-extended, depending on the isSigned parameter,
9132/// from an integer type half its size.
9134 bool isSigned) {
9135 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
9136 EVT VT = N->getValueType(0);
9137 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
9138 SDNode *BVN = N->getOperand(0).getNode();
9139 if (BVN->getValueType(0) != MVT::v4i32 ||
9140 BVN->getOpcode() != ISD::BUILD_VECTOR)
9141 return false;
9142 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9143 unsigned HiElt = 1 - LoElt;
9148 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
9149 return false;
9150 if (isSigned) {
9151 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
9152 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
9153 return true;
9154 } else {
9155 if (Hi0->isZero() && Hi1->isZero())
9156 return true;
9157 }
9158 return false;
9159 }
9160
9161 if (N->getOpcode() != ISD::BUILD_VECTOR)
9162 return false;
9163
9164 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9165 SDNode *Elt = N->getOperand(i).getNode();
9167 unsigned EltSize = VT.getScalarSizeInBits();
9168 unsigned HalfSize = EltSize / 2;
9169 if (isSigned) {
9170 if (!isIntN(HalfSize, C->getSExtValue()))
9171 return false;
9172 } else {
9173 if (!isUIntN(HalfSize, C->getZExtValue()))
9174 return false;
9175 }
9176 continue;
9177 }
9178 return false;
9179 }
9180
9181 return true;
9182}
9183
9184/// isSignExtended - Check if a node is a vector value that is sign-extended
9185/// or a constant BUILD_VECTOR with sign-extended elements.
9187 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
9188 return true;
9189 if (isExtendedBUILD_VECTOR(N, DAG, true))
9190 return true;
9191 return false;
9192}
9193
9194/// isZeroExtended - Check if a node is a vector value that is zero-extended (or
9195/// any-extended) or a constant BUILD_VECTOR with zero-extended elements.
9197 if (N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND ||
9199 return true;
9200 if (isExtendedBUILD_VECTOR(N, DAG, false))
9201 return true;
9202 return false;
9203}
9204
9205static EVT getExtensionTo64Bits(const EVT &OrigVT) {
9206 if (OrigVT.getSizeInBits() >= 64)
9207 return OrigVT;
9208
9209 assert(OrigVT.isSimple() && "Expecting a simple value type");
9210
9211 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
9212 switch (OrigSimpleTy) {
9213 default: llvm_unreachable("Unexpected Vector Type");
9214 case MVT::v2i8:
9215 case MVT::v2i16:
9216 return MVT::v2i32;
9217 case MVT::v4i8:
9218 return MVT::v4i16;
9219 }
9220}
9221
9222/// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
9223/// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
9224/// We insert the required extension here to get the vector to fill a D register.
9226 const EVT &OrigTy,
9227 const EVT &ExtTy,
9228 unsigned ExtOpcode) {
9229 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
9230 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
9231 // 64-bits we need to insert a new extension so that it will be 64-bits.
9232 assert(ExtTy.is128BitVector() && "Unexpected extension size");
9233 if (OrigTy.getSizeInBits() >= 64)
9234 return N;
9235
9236 // Must extend size to at least 64 bits to be used as an operand for VMULL.
9237 EVT NewVT = getExtensionTo64Bits(OrigTy);
9238
9239 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
9240}
9241
9242/// SkipLoadExtensionForVMULL - return a load of the original vector size that
9243/// does not do any sign/zero extension. If the original vector is less
9244/// than 64 bits, an appropriate extension will be added after the load to
9245/// reach a total size of 64 bits. We have to add the extension separately
9246/// because ARM does not have a sign/zero extending load for vectors.
9248 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
9249
9250 // The load already has the right type.
9251 if (ExtendedTy == LD->getMemoryVT())
9252 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
9253 LD->getBasePtr(), LD->getPointerInfo(), LD->getAlign(),
9254 LD->getMemOperand()->getFlags());
9255
9256 // We need to create a zextload/sextload. We cannot just create a load
9257 // followed by a zext/zext node because LowerMUL is also run during normal
9258 // operation legalization where we can't create illegal types.
9259 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
9260 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
9261 LD->getMemoryVT(), LD->getAlign(),
9262 LD->getMemOperand()->getFlags());
9263}
9264
9265/// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
9266/// ANY_EXTEND, extending load, or BUILD_VECTOR with extended elements, return
9267/// the unextended value. The unextended vector should be 64 bits so that it can
9268/// be used as an operand to a VMULL instruction. If the original vector size
9269/// before extension is less than 64 bits we add a an extension to resize
9270/// the vector to 64 bits.
9272 if (N->getOpcode() == ISD::SIGN_EXTEND ||
9273 N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND)
9274 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
9275 N->getOperand(0)->getValueType(0),
9276 N->getValueType(0),
9277 N->getOpcode());
9278
9279 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9280 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
9281 "Expected extending load");
9282
9283 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
9284 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
9285 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9286 SDValue extLoad =
9287 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
9288 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
9289
9290 return newLoad;
9291 }
9292
9293 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
9294 // have been legalized as a BITCAST from v4i32.
9295 if (N->getOpcode() == ISD::BITCAST) {
9296 SDNode *BVN = N->getOperand(0).getNode();
9298 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
9299 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9300 return DAG.getBuildVector(
9301 MVT::v2i32, SDLoc(N),
9302 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
9303 }
9304 // Construct a new BUILD_VECTOR with elements truncated to half the size.
9305 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
9306 EVT VT = N->getValueType(0);
9307 unsigned EltSize = VT.getScalarSizeInBits() / 2;
9308 unsigned NumElts = VT.getVectorNumElements();
9309 MVT TruncVT = MVT::getIntegerVT(EltSize);
9311 SDLoc dl(N);
9312 for (unsigned i = 0; i != NumElts; ++i) {
9313 const APInt &CInt = N->getConstantOperandAPInt(i);
9314 // Element types smaller than 32 bits are not legal, so use i32 elements.
9315 // The values are implicitly truncated so sext vs. zext doesn't matter.
9316 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
9317 }
9318 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
9319}
9320
9321static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
9322 unsigned Opcode = N->getOpcode();
9323 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
9324 SDNode *N0 = N->getOperand(0).getNode();
9325 SDNode *N1 = N->getOperand(1).getNode();
9326 return N0->hasOneUse() && N1->hasOneUse() &&
9327 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
9328 }
9329 return false;
9330}
9331
9332static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
9333 unsigned Opcode = N->getOpcode();
9334 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
9335 SDNode *N0 = N->getOperand(0).getNode();
9336 SDNode *N1 = N->getOperand(1).getNode();
9337 return N0->hasOneUse() && N1->hasOneUse() &&
9338 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
9339 }
9340 return false;
9341}
9342
9344 // Multiplications are only custom-lowered for 128-bit vectors so that
9345 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
9346 EVT VT = Op.getValueType();
9347 assert(VT.is128BitVector() && VT.isInteger() &&
9348 "unexpected type for custom-lowering ISD::MUL");
9349 SDNode *N0 = Op.getOperand(0).getNode();
9350 SDNode *N1 = Op.getOperand(1).getNode();
9351 unsigned NewOpc = 0;
9352 bool isMLA = false;
9353 bool isN0SExt = isSignExtended(N0, DAG);
9354 bool isN1SExt = isSignExtended(N1, DAG);
9355 if (isN0SExt && isN1SExt)
9356 NewOpc = ARMISD::VMULLs;
9357 else {
9358 bool isN0ZExt = isZeroExtended(N0, DAG);
9359 bool isN1ZExt = isZeroExtended(N1, DAG);
9360 if (isN0ZExt && isN1ZExt)
9361 NewOpc = ARMISD::VMULLu;
9362 else if (isN1SExt || isN1ZExt) {
9363 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
9364 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
9365 if (isN1SExt && isAddSubSExt(N0, DAG)) {
9366 NewOpc = ARMISD::VMULLs;
9367 isMLA = true;
9368 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
9369 NewOpc = ARMISD::VMULLu;
9370 isMLA = true;
9371 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
9372 std::swap(N0, N1);
9373 NewOpc = ARMISD::VMULLu;
9374 isMLA = true;
9375 }
9376 }
9377
9378 if (!NewOpc) {
9379 if (VT == MVT::v2i64)
9380 // Fall through to expand this. It is not legal.
9381 return SDValue();
9382 else
9383 // Other vector multiplications are legal.
9384 return Op;
9385 }
9386 }
9387
9388 // Legalize to a VMULL instruction.
9389 SDLoc DL(Op);
9390 SDValue Op0;
9391 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
9392 if (!isMLA) {
9393 Op0 = SkipExtensionForVMULL(N0, DAG);
9395 Op1.getValueType().is64BitVector() &&
9396 "unexpected types for extended operands to VMULL");
9397 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
9398 }
9399
9400 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
9401 // isel lowering to take advantage of no-stall back to back vmul + vmla.
9402 // vmull q0, d4, d6
9403 // vmlal q0, d5, d6
9404 // is faster than
9405 // vaddl q0, d4, d5
9406 // vmovl q1, d6
9407 // vmul q0, q0, q1
9408 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
9409 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
9410 EVT Op1VT = Op1.getValueType();
9411 return DAG.getNode(N0->getOpcode(), DL, VT,
9412 DAG.getNode(NewOpc, DL, VT,
9413 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
9414 DAG.getNode(NewOpc, DL, VT,
9415 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
9416}
9417
9419 SelectionDAG &DAG) {
9420 // TODO: Should this propagate fast-math-flags?
9421
9422 // Convert to float
9423 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
9424 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
9425 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
9426 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
9427 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
9428 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
9429 // Get reciprocal estimate.
9430 // float4 recip = vrecpeq_f32(yf);
9431 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9432 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9433 Y);
9434 // Because char has a smaller range than uchar, we can actually get away
9435 // without any newton steps. This requires that we use a weird bias
9436 // of 0xb000, however (again, this has been exhaustively tested).
9437 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
9438 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
9439 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
9440 Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
9441 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
9442 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
9443 // Convert back to short.
9444 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
9445 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
9446 return X;
9447}
9448
9450 SelectionDAG &DAG) {
9451 // TODO: Should this propagate fast-math-flags?
9452
9453 SDValue N2;
9454 // Convert to float.
9455 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
9456 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
9457 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
9458 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
9459 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
9460 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
9461
9462 // Use reciprocal estimate and one refinement step.
9463 // float4 recip = vrecpeq_f32(yf);
9464 // recip *= vrecpsq_f32(yf, recip);
9465 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9466 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9467 N1);
9468 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9469 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9470 N1, N2);
9471 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9472 // Because short has a smaller range than ushort, we can actually get away
9473 // with only a single newton step. This requires that we use a weird bias
9474 // of 89, however (again, this has been exhaustively tested).
9475 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
9476 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
9477 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
9478 N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
9479 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
9480 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9481 // Convert back to integer and return.
9482 // return vmovn_s32(vcvt_s32_f32(result));
9483 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9484 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9485 return N0;
9486}
9487
9489 const ARMSubtarget *ST) {
9490 EVT VT = Op.getValueType();
9491 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
9492 "unexpected type for custom-lowering ISD::SDIV");
9493
9494 SDLoc dl(Op);
9495 SDValue N0 = Op.getOperand(0);
9496 SDValue N1 = Op.getOperand(1);
9497 SDValue N2, N3;
9498
9499 if (VT == MVT::v8i8) {
9500 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
9501 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
9502
9503 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9504 DAG.getIntPtrConstant(4, dl));
9505 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9506 DAG.getIntPtrConstant(4, dl));
9507 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9508 DAG.getIntPtrConstant(0, dl));
9509 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9510 DAG.getIntPtrConstant(0, dl));
9511
9512 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
9513 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
9514
9515 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9516 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9517
9518 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
9519 return N0;
9520 }
9521 return LowerSDIV_v4i16(N0, N1, dl, DAG);
9522}
9523
9525 const ARMSubtarget *ST) {
9526 // TODO: Should this propagate fast-math-flags?
9527 EVT VT = Op.getValueType();
9528 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
9529 "unexpected type for custom-lowering ISD::UDIV");
9530
9531 SDLoc dl(Op);
9532 SDValue N0 = Op.getOperand(0);
9533 SDValue N1 = Op.getOperand(1);
9534 SDValue N2, N3;
9535
9536 if (VT == MVT::v8i8) {
9537 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
9538 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
9539
9540 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9541 DAG.getIntPtrConstant(4, dl));
9542 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9543 DAG.getIntPtrConstant(4, dl));
9544 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9545 DAG.getIntPtrConstant(0, dl));
9546 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9547 DAG.getIntPtrConstant(0, dl));
9548
9549 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
9550 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
9551
9552 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9553 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9554
9555 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
9556 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
9557 MVT::i32),
9558 N0);
9559 return N0;
9560 }
9561
9562 // v4i16 sdiv ... Convert to float.
9563 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
9564 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
9565 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
9566 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
9567 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
9568 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
9569
9570 // Use reciprocal estimate and two refinement steps.
9571 // float4 recip = vrecpeq_f32(yf);
9572 // recip *= vrecpsq_f32(yf, recip);
9573 // recip *= vrecpsq_f32(yf, recip);
9574 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9575 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9576 BN1);
9577 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9578 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9579 BN1, N2);
9580 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9581 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9582 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9583 BN1, N2);
9584 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9585 // Simply multiplying by the reciprocal estimate can leave us a few ulps
9586 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
9587 // and that it will never cause us to return an answer too large).
9588 // float4 result = as_float4(as_int4(xf*recip) + 2);
9589 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
9590 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
9591 N1 = DAG.getConstant(2, dl, MVT::v4i32);
9592 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
9593 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9594 // Convert back to integer and return.
9595 // return vmovn_u32(vcvt_s32_f32(result));
9596 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9597 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9598 return N0;
9599}
9600
9602 unsigned Opcode, bool IsSigned) {
9603 EVT VT0 = Op.getValue(0).getValueType();
9604 EVT VT1 = Op.getValue(1).getValueType();
9605
9606 bool InvertCarry = Opcode == ARMISD::SUBE;
9607 SDValue OpLHS = Op.getOperand(0);
9608 SDValue OpRHS = Op.getOperand(1);
9609 SDValue OpCarryIn = valueToCarryFlag(Op.getOperand(2), DAG, InvertCarry);
9610
9611 SDLoc DL(Op);
9612
9613 SDValue Result = DAG.getNode(Opcode, DL, DAG.getVTList(VT0, MVT::i32), OpLHS,
9614 OpRHS, OpCarryIn);
9615
9616 SDValue OutFlag =
9617 IsSigned ? overflowFlagToValue(Result.getValue(1), VT1, DAG)
9618 : carryFlagToValue(Result.getValue(1), VT1, DAG, InvertCarry);
9619
9620 return DAG.getMergeValues({Result, OutFlag}, DL);
9621}
9622
9623SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
9624 bool Signed,
9625 SDValue &Chain) const {
9626 EVT VT = Op.getValueType();
9627 assert((VT == MVT::i32 || VT == MVT::i64) &&
9628 "unexpected type for custom lowering DIV");
9629 SDLoc dl(Op);
9630
9631 const auto &DL = DAG.getDataLayout();
9632 RTLIB::Libcall LC;
9633 if (Signed)
9634 LC = VT == MVT::i32 ? RTLIB::SDIVREM_I32 : RTLIB::SDIVREM_I64;
9635 else
9636 LC = VT == MVT::i32 ? RTLIB::UDIVREM_I32 : RTLIB::UDIVREM_I64;
9637
9638 RTLIB::LibcallImpl LCImpl = DAG.getLibcalls().getLibcallImpl(LC);
9639 SDValue ES = DAG.getExternalSymbol(LCImpl, getPointerTy(DL));
9640
9642
9643 for (auto AI : {1, 0}) {
9644 SDValue Operand = Op.getOperand(AI);
9645 Args.emplace_back(Operand,
9646 Operand.getValueType().getTypeForEVT(*DAG.getContext()));
9647 }
9648
9649 CallLoweringInfo CLI(DAG);
9650 CLI.setDebugLoc(dl).setChain(Chain).setCallee(
9652 VT.getTypeForEVT(*DAG.getContext()), ES, std::move(Args));
9653
9654 return LowerCallTo(CLI).first;
9655}
9656
9657// This is a code size optimisation: return the original SDIV node to
9658// DAGCombiner when we don't want to expand SDIV into a sequence of
9659// instructions, and an empty node otherwise which will cause the
9660// SDIV to be expanded in DAGCombine.
9661SDValue
9662ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9663 SelectionDAG &DAG,
9664 SmallVectorImpl<SDNode *> &Created) const {
9665 // TODO: Support SREM
9666 if (N->getOpcode() != ISD::SDIV)
9667 return SDValue();
9668
9669 const auto &ST = DAG.getSubtarget<ARMSubtarget>();
9670 const bool MinSize = ST.hasMinSize();
9671 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
9672 : ST.hasDivideInARMMode();
9673
9674 // Don't touch vector types; rewriting this may lead to scalarizing
9675 // the int divs.
9676 if (N->getOperand(0).getValueType().isVector())
9677 return SDValue();
9678
9679 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
9680 // hwdiv support for this to be really profitable.
9681 if (!(MinSize && HasDivide))
9682 return SDValue();
9683
9684 // ARM mode is a bit simpler than Thumb: we can handle large power
9685 // of 2 immediates with 1 mov instruction; no further checks required,
9686 // just return the sdiv node.
9687 if (!ST.isThumb())
9688 return SDValue(N, 0);
9689
9690 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
9691 // and thus lose the code size benefits of a MOVS that requires only 2.
9692 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
9693 // but as it's doing exactly this, it's not worth the trouble to get TTI.
9694 if (Divisor.sgt(128))
9695 return SDValue();
9696
9697 return SDValue(N, 0);
9698}
9699
9700SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
9701 bool Signed) const {
9702 assert(Op.getValueType() == MVT::i32 &&
9703 "unexpected type for custom lowering DIV");
9704 SDLoc dl(Op);
9705
9706 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
9707 DAG.getEntryNode(), Op.getOperand(1));
9708
9709 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9710}
9711
9713 SDLoc DL(N);
9714 SDValue Op = N->getOperand(1);
9715 if (N->getValueType(0) == MVT::i32)
9716 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
9717 SDValue Lo, Hi;
9718 std::tie(Lo, Hi) = DAG.SplitScalar(Op, DL, MVT::i32, MVT::i32);
9719 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
9720 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
9721}
9722
9723void ARMTargetLowering::ExpandDIV_Windows(
9724 SDValue Op, SelectionDAG &DAG, bool Signed,
9726 const auto &DL = DAG.getDataLayout();
9727
9728 assert(Op.getValueType() == MVT::i64 &&
9729 "unexpected type for custom lowering DIV");
9730 SDLoc dl(Op);
9731
9732 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
9733
9734 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9735
9736 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
9737 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
9738 DAG.getConstant(32, dl, getPointerTy(DL)));
9739 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
9740
9741 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lower, Upper));
9742}
9743
9744std::pair<SDValue, SDValue>
9745ARMTargetLowering::LowerAEABIUnalignedLoad(SDValue Op,
9746 SelectionDAG &DAG) const {
9747 // If we have an unaligned load from a i32 or i64 that would normally be
9748 // split into separate ldrb's, we can use the __aeabi_uread4/__aeabi_uread8
9749 // functions instead.
9750 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
9751 EVT MemVT = LD->getMemoryVT();
9752 if (MemVT != MVT::i32 && MemVT != MVT::i64)
9753 return std::make_pair(SDValue(), SDValue());
9754
9755 const auto &MF = DAG.getMachineFunction();
9756 unsigned AS = LD->getAddressSpace();
9757 Align Alignment = LD->getAlign();
9758 const DataLayout &DL = DAG.getDataLayout();
9759 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9760 RTLIB::Libcall LC =
9761 (MemVT == MVT::i32) ? RTLIB::AEABI_UREAD4 : RTLIB::AEABI_UREAD8;
9762
9763 if (MF.getFunction().hasMinSize() && !AllowsUnaligned &&
9764 Alignment <= llvm::Align(2) && DAG.getLibcalls().getLibcallImpl(LC)) {
9765 MakeLibCallOptions Opts;
9766 SDLoc dl(Op);
9767
9768 auto Pair = makeLibCall(DAG, LC, MemVT.getSimpleVT(), LD->getBasePtr(),
9769 Opts, dl, LD->getChain());
9770
9771 // If necessary, extend the node to 64bit
9772 if (LD->getExtensionType() != ISD::NON_EXTLOAD) {
9773 unsigned ExtType = LD->getExtensionType() == ISD::SEXTLOAD
9776 SDValue EN = DAG.getNode(ExtType, dl, LD->getValueType(0), Pair.first);
9777 Pair.first = EN;
9778 }
9779 return Pair;
9780 }
9781
9782 // Default expand to individual loads
9783 if (!allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Alignment))
9784 return expandUnalignedLoad(LD, DAG);
9785 return std::make_pair(SDValue(), SDValue());
9786}
9787
9788SDValue ARMTargetLowering::LowerAEABIUnalignedStore(SDValue Op,
9789 SelectionDAG &DAG) const {
9790 // If we have an unaligned store to a i32 or i64 that would normally be
9791 // split into separate ldrb's, we can use the __aeabi_uwrite4/__aeabi_uwrite8
9792 // functions instead.
9793 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9794 EVT MemVT = ST->getMemoryVT();
9795 if (MemVT != MVT::i32 && MemVT != MVT::i64)
9796 return SDValue();
9797
9798 const auto &MF = DAG.getMachineFunction();
9799 unsigned AS = ST->getAddressSpace();
9800 Align Alignment = ST->getAlign();
9801 const DataLayout &DL = DAG.getDataLayout();
9802 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9803 RTLIB::Libcall LC =
9804 (MemVT == MVT::i32) ? RTLIB::AEABI_UWRITE4 : RTLIB::AEABI_UWRITE8;
9805
9806 if (MF.getFunction().hasMinSize() && !AllowsUnaligned &&
9807 Alignment <= llvm::Align(2) && DAG.getLibcalls().getLibcallImpl(LC)) {
9808
9809 SDLoc dl(Op);
9810
9811 // If necessary, trunc the value to 32bit
9812 SDValue StoreVal = ST->getOperand(1);
9813 if (ST->isTruncatingStore())
9814 StoreVal = DAG.getNode(ISD::TRUNCATE, dl, MemVT, ST->getOperand(1));
9815
9816 MakeLibCallOptions Opts;
9817 auto CallResult =
9818 makeLibCall(DAG, LC, MVT::isVoid, {StoreVal, ST->getBasePtr()}, Opts,
9819 dl, ST->getChain());
9820
9821 return CallResult.second;
9822 }
9823
9824 // Default expand to individual stores
9825 if (!allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Alignment))
9826 return expandUnalignedStore(ST, DAG);
9827 return SDValue();
9828}
9829
9831 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
9832 EVT MemVT = LD->getMemoryVT();
9833 assert((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9834 MemVT == MVT::v16i1) &&
9835 "Expected a predicate type!");
9836 assert(MemVT == Op.getValueType());
9837 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
9838 "Expected a non-extending load");
9839 assert(LD->isUnindexed() && "Expected a unindexed load");
9840
9841 // The basic MVE VLDR on a v2i1/v4i1/v8i1 actually loads the entire 16bit
9842 // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We
9843 // need to make sure that 8/4/2 bits are actually loaded into the correct
9844 // place, which means loading the value and then shuffling the values into
9845 // the bottom bits of the predicate.
9846 // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect
9847 // for BE).
9848 // Speaking of BE, apparently the rest of llvm will assume a reverse order to
9849 // a natural VMSR(load), so needs to be reversed.
9850
9851 SDLoc dl(Op);
9852 SDValue Load = DAG.getExtLoad(
9853 ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(),
9855 LD->getMemOperand());
9856 SDValue Val = Load;
9857 if (DAG.getDataLayout().isBigEndian())
9858 Val = DAG.getNode(ISD::SRL, dl, MVT::i32,
9859 DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Load),
9860 DAG.getConstant(32 - MemVT.getSizeInBits(), dl, MVT::i32));
9861 SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Val);
9862 if (MemVT != MVT::v16i1)
9863 Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred,
9864 DAG.getConstant(0, dl, MVT::i32));
9865 return DAG.getMergeValues({Pred, Load.getValue(1)}, dl);
9866}
9867
9868void ARMTargetLowering::LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results,
9869 SelectionDAG &DAG) const {
9870 LoadSDNode *LD = cast<LoadSDNode>(N);
9871 EVT MemVT = LD->getMemoryVT();
9872
9873 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9874 !Subtarget->isThumb1Only() && LD->isVolatile() &&
9875 LD->getAlign() >= Subtarget->getDualLoadStoreAlignment()) {
9876 assert(LD->isUnindexed() && "Loads should be unindexed at this point.");
9877 SDLoc dl(N);
9879 ARMISD::LDRD, dl, DAG.getVTList({MVT::i32, MVT::i32, MVT::Other}),
9880 {LD->getChain(), LD->getBasePtr()}, MemVT, LD->getMemOperand());
9881 SDValue Lo = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 0 : 1);
9882 SDValue Hi = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 1 : 0);
9883 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
9884 Results.append({Pair, Result.getValue(2)});
9885 } else if (MemVT == MVT::i32 || MemVT == MVT::i64) {
9886 auto Pair = LowerAEABIUnalignedLoad(SDValue(N, 0), DAG);
9887 if (Pair.first) {
9888 Results.push_back(Pair.first);
9889 Results.push_back(Pair.second);
9890 }
9891 }
9892}
9893
9895 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9896 EVT MemVT = ST->getMemoryVT();
9897 assert((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9898 MemVT == MVT::v16i1) &&
9899 "Expected a predicate type!");
9900 assert(MemVT == ST->getValue().getValueType());
9901 assert(!ST->isTruncatingStore() && "Expected a non-extending store");
9902 assert(ST->isUnindexed() && "Expected a unindexed store");
9903
9904 // Only store the v2i1 or v4i1 or v8i1 worth of bits, via a buildvector with
9905 // top bits unset and a scalar store.
9906 SDLoc dl(Op);
9907 SDValue Build = ST->getValue();
9908 if (MemVT != MVT::v16i1) {
9910 for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++) {
9911 unsigned Elt = DAG.getDataLayout().isBigEndian()
9912 ? MemVT.getVectorNumElements() - I - 1
9913 : I;
9914 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build,
9915 DAG.getConstant(Elt, dl, MVT::i32)));
9916 }
9917 for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++)
9918 Ops.push_back(DAG.getUNDEF(MVT::i32));
9919 Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops);
9920 }
9921 SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build);
9922 if (MemVT == MVT::v16i1 && DAG.getDataLayout().isBigEndian())
9923 GRP = DAG.getNode(ISD::SRL, dl, MVT::i32,
9924 DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, GRP),
9925 DAG.getConstant(16, dl, MVT::i32));
9926 return DAG.getTruncStore(
9927 ST->getChain(), dl, GRP, ST->getBasePtr(),
9929 ST->getMemOperand());
9930}
9931
9932SDValue ARMTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG,
9933 const ARMSubtarget *Subtarget) const {
9934 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9935 EVT MemVT = ST->getMemoryVT();
9936
9937 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9938 !Subtarget->isThumb1Only() && ST->isVolatile() &&
9939 ST->getAlign() >= Subtarget->getDualLoadStoreAlignment()) {
9940 assert(ST->isUnindexed() && "Stores should be unindexed at this point.");
9941 SDNode *N = Op.getNode();
9942 SDLoc dl(N);
9943
9944 SDValue Lo = DAG.getNode(
9945 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9946 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 0 : 1, dl,
9947 MVT::i32));
9948 SDValue Hi = DAG.getNode(
9949 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9950 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 1 : 0, dl,
9951 MVT::i32));
9952
9953 return DAG.getMemIntrinsicNode(ARMISD::STRD, dl, DAG.getVTList(MVT::Other),
9954 {ST->getChain(), Lo, Hi, ST->getBasePtr()},
9955 MemVT, ST->getMemOperand());
9956 } else if (Subtarget->hasMVEIntegerOps() &&
9957 ((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9958 MemVT == MVT::v16i1))) {
9959 return LowerPredicateStore(Op, DAG);
9960 } else if (MemVT == MVT::i32 || MemVT == MVT::i64) {
9961 return LowerAEABIUnalignedStore(Op, DAG);
9962 }
9963 return SDValue();
9964}
9965
9966static bool isZeroVector(SDValue N) {
9967 return (ISD::isBuildVectorAllZeros(N) || (N->getOpcode() == ARMISD::VMOVIMM &&
9968 isNullConstant(N->getOperand(0))));
9969}
9970
9973 MVT VT = Op.getSimpleValueType();
9974 SDValue Mask = N->getMask();
9975 SDValue PassThru = N->getPassThru();
9976 SDLoc dl(Op);
9977
9978 if (isZeroVector(PassThru))
9979 return Op;
9980
9981 // MVE Masked loads use zero as the passthru value. Here we convert undef to
9982 // zero too, and other values are lowered to a select.
9983 SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
9984 DAG.getTargetConstant(0, dl, MVT::i32));
9985 SDValue NewLoad = DAG.getMaskedLoad(
9986 VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec,
9987 N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
9988 N->getExtensionType(), N->isExpandingLoad());
9989 SDValue Combo = NewLoad;
9990 bool PassThruIsCastZero = (PassThru.getOpcode() == ISD::BITCAST ||
9991 PassThru.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
9992 isZeroVector(PassThru->getOperand(0));
9993 if (!PassThru.isUndef() && !PassThruIsCastZero)
9994 Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
9995 return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl);
9996}
9997
9999 const ARMSubtarget *ST) {
10000 if (!ST->hasMVEIntegerOps())
10001 return SDValue();
10002
10003 SDLoc dl(Op);
10004 unsigned BaseOpcode = 0;
10005 switch (Op->getOpcode()) {
10006 default: llvm_unreachable("Expected VECREDUCE opcode");
10007 case ISD::VECREDUCE_FADD: BaseOpcode = ISD::FADD; break;
10008 case ISD::VECREDUCE_FMUL: BaseOpcode = ISD::FMUL; break;
10009 case ISD::VECREDUCE_MUL: BaseOpcode = ISD::MUL; break;
10010 case ISD::VECREDUCE_AND: BaseOpcode = ISD::AND; break;
10011 case ISD::VECREDUCE_OR: BaseOpcode = ISD::OR; break;
10012 case ISD::VECREDUCE_XOR: BaseOpcode = ISD::XOR; break;
10013 case ISD::VECREDUCE_FMAX: BaseOpcode = ISD::FMAXNUM; break;
10014 case ISD::VECREDUCE_FMIN: BaseOpcode = ISD::FMINNUM; break;
10015 }
10016
10017 SDValue Op0 = Op->getOperand(0);
10018 EVT VT = Op0.getValueType();
10019 EVT EltVT = VT.getVectorElementType();
10020 unsigned NumElts = VT.getVectorNumElements();
10021 unsigned NumActiveLanes = NumElts;
10022
10023 assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 ||
10024 NumActiveLanes == 2) &&
10025 "Only expected a power 2 vector size");
10026
10027 // Use Mul(X, Rev(X)) until 4 items remain. Going down to 4 vector elements
10028 // allows us to easily extract vector elements from the lanes.
10029 while (NumActiveLanes > 4) {
10030 unsigned RevOpcode = NumActiveLanes == 16 ? ARMISD::VREV16 : ARMISD::VREV32;
10031 SDValue Rev = DAG.getNode(RevOpcode, dl, VT, Op0);
10032 Op0 = DAG.getNode(BaseOpcode, dl, VT, Op0, Rev);
10033 NumActiveLanes /= 2;
10034 }
10035
10036 SDValue Res;
10037 if (NumActiveLanes == 4) {
10038 // The remaining 4 elements are summed sequentially
10039 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10040 DAG.getConstant(0 * NumElts / 4, dl, MVT::i32));
10041 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10042 DAG.getConstant(1 * NumElts / 4, dl, MVT::i32));
10043 SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10044 DAG.getConstant(2 * NumElts / 4, dl, MVT::i32));
10045 SDValue Ext3 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10046 DAG.getConstant(3 * NumElts / 4, dl, MVT::i32));
10047 SDValue Res0 = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
10048 SDValue Res1 = DAG.getNode(BaseOpcode, dl, EltVT, Ext2, Ext3, Op->getFlags());
10049 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res0, Res1, Op->getFlags());
10050 } else {
10051 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10052 DAG.getConstant(0, dl, MVT::i32));
10053 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10054 DAG.getConstant(1, dl, MVT::i32));
10055 Res = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
10056 }
10057
10058 // Result type may be wider than element type.
10059 if (EltVT != Op->getValueType(0))
10060 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Op->getValueType(0), Res);
10061 return Res;
10062}
10063
10065 const ARMSubtarget *ST) {
10066 if (!ST->hasMVEFloatOps())
10067 return SDValue();
10068 return LowerVecReduce(Op, DAG, ST);
10069}
10070
10072 const ARMSubtarget *ST) {
10073 if (!ST->hasNEON())
10074 return SDValue();
10075
10076 SDLoc dl(Op);
10077 SDValue Op0 = Op->getOperand(0);
10078 EVT VT = Op0.getValueType();
10079 EVT EltVT = VT.getVectorElementType();
10080
10081 unsigned PairwiseIntrinsic = 0;
10082 switch (Op->getOpcode()) {
10083 default:
10084 llvm_unreachable("Expected VECREDUCE opcode");
10086 PairwiseIntrinsic = Intrinsic::arm_neon_vpminu;
10087 break;
10089 PairwiseIntrinsic = Intrinsic::arm_neon_vpmaxu;
10090 break;
10092 PairwiseIntrinsic = Intrinsic::arm_neon_vpmins;
10093 break;
10095 PairwiseIntrinsic = Intrinsic::arm_neon_vpmaxs;
10096 break;
10097 }
10098 SDValue PairwiseOp = DAG.getConstant(PairwiseIntrinsic, dl, MVT::i32);
10099
10100 unsigned NumElts = VT.getVectorNumElements();
10101 unsigned NumActiveLanes = NumElts;
10102
10103 assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 ||
10104 NumActiveLanes == 2) &&
10105 "Only expected a power 2 vector size");
10106
10107 // Split 128-bit vectors, since vpmin/max takes 2 64-bit vectors.
10108 if (VT.is128BitVector()) {
10109 SDValue Lo, Hi;
10110 std::tie(Lo, Hi) = DAG.SplitVector(Op0, dl);
10111 VT = Lo.getValueType();
10112 Op0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, {PairwiseOp, Lo, Hi});
10113 NumActiveLanes /= 2;
10114 }
10115
10116 // Use pairwise reductions until one lane remains
10117 while (NumActiveLanes > 1) {
10118 Op0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, {PairwiseOp, Op0, Op0});
10119 NumActiveLanes /= 2;
10120 }
10121
10122 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10123 DAG.getConstant(0, dl, MVT::i32));
10124
10125 // Result type may be wider than element type.
10126 if (EltVT != Op.getValueType()) {
10127 unsigned Extend = 0;
10128 switch (Op->getOpcode()) {
10129 default:
10130 llvm_unreachable("Expected VECREDUCE opcode");
10133 Extend = ISD::ZERO_EXTEND;
10134 break;
10137 Extend = ISD::SIGN_EXTEND;
10138 break;
10139 }
10140 Res = DAG.getNode(Extend, dl, Op.getValueType(), Res);
10141 }
10142 return Res;
10143}
10144
10147 SelectionDAG &DAG,
10148 const ARMSubtarget *Subtarget) {
10149 SDLoc DL(N);
10150 // Under Power Management extensions, the cycle-count is:
10151 // mrc p15, #0, <Rt>, c9, c13, #0
10152 SDValue Ops[] = { N->getOperand(0), // Chain
10153 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
10154 DAG.getTargetConstant(15, DL, MVT::i32),
10155 DAG.getTargetConstant(0, DL, MVT::i32),
10156 DAG.getTargetConstant(9, DL, MVT::i32),
10157 DAG.getTargetConstant(13, DL, MVT::i32),
10158 DAG.getTargetConstant(0, DL, MVT::i32)
10159 };
10160
10161 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
10162 DAG.getVTList(MVT::i32, MVT::Other), Ops);
10163 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
10164 DAG.getConstant(0, DL, MVT::i32)));
10165 Results.push_back(Cycles32.getValue(1));
10166}
10167
10169 SDValue V1) {
10170 SDLoc dl(V0.getNode());
10171 SDValue RegClass =
10172 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
10173 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
10174 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
10175 const SDValue Ops[] = {RegClass, V0, SubReg0, V1, SubReg1};
10176 return SDValue(
10177 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
10178}
10179
10181 SDLoc dl(V.getNode());
10182 auto [VLo, VHi] = DAG.SplitScalar(V, dl, MVT::i32, MVT::i32);
10183 bool isBigEndian = DAG.getDataLayout().isBigEndian();
10184 if (isBigEndian)
10185 std::swap(VLo, VHi);
10186 return createGPRPairNode2xi32(DAG, VLo, VHi);
10187}
10188
10191 SelectionDAG &DAG) {
10192 assert(N->getValueType(0) == MVT::i64 &&
10193 "AtomicCmpSwap on types less than 64 should be legal");
10194 SDValue Ops[] = {
10195 createGPRPairNode2xi32(DAG, N->getOperand(1),
10196 DAG.getUNDEF(MVT::i32)), // pointer, temp
10197 createGPRPairNodei64(DAG, N->getOperand(2)), // expected
10198 createGPRPairNodei64(DAG, N->getOperand(3)), // new
10199 N->getOperand(0), // chain in
10200 };
10201 SDNode *CmpSwap = DAG.getMachineNode(
10202 ARM::CMP_SWAP_64, SDLoc(N),
10203 DAG.getVTList(MVT::Untyped, MVT::Untyped, MVT::Other), Ops);
10204
10205 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
10206 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
10207
10208 bool isBigEndian = DAG.getDataLayout().isBigEndian();
10209
10210 SDValue Lo =
10211 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
10212 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
10213 SDValue Hi =
10214 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
10215 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
10216 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i64, Lo, Hi));
10217 Results.push_back(SDValue(CmpSwap, 2));
10218}
10219
10220SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const {
10221 SDLoc dl(Op);
10222 EVT VT = Op.getValueType();
10223 SDValue Chain = Op.getOperand(0);
10224 SDValue LHS = Op.getOperand(1);
10225 SDValue RHS = Op.getOperand(2);
10226 ISD::CondCode CC = Op.getOperandCondCode(3);
10227 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
10228
10229 // If we don't have instructions of this float type then soften to a libcall
10230 // and use SETCC instead.
10231 if (isUnsupportedFloatingType(LHS.getValueType())) {
10232 softenSetCCOperands(DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS,
10233 Chain, IsSignaling);
10234 if (!RHS.getNode()) {
10235 RHS = DAG.getConstant(0, dl, LHS.getValueType());
10236 CC = ISD::SETNE;
10237 }
10238 SDValue Result = DAG.getNode(ISD::SETCC, dl, VT, LHS, RHS,
10239 DAG.getCondCode(CC));
10240 return DAG.getMergeValues({Result, Chain}, dl);
10241 }
10242
10243 ARMCC::CondCodes CondCode, CondCode2;
10244 FPCCToARMCC(CC, CondCode, CondCode2);
10245
10246 SDValue True = DAG.getConstant(1, dl, VT);
10247 SDValue False = DAG.getConstant(0, dl, VT);
10248 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
10249 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
10250 SDValue Result = getCMOV(dl, VT, False, True, ARMcc, Cmp, DAG);
10251 if (CondCode2 != ARMCC::AL) {
10252 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
10253 Result = getCMOV(dl, VT, Result, True, ARMcc, Cmp, DAG);
10254 }
10255 return DAG.getMergeValues({Result, Chain}, dl);
10256}
10257
10258SDValue ARMTargetLowering::LowerSPONENTRY(SDValue Op, SelectionDAG &DAG) const {
10259 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10260
10261 EVT VT = getPointerTy(DAG.getDataLayout());
10262 int FI = MFI.CreateFixedObject(4, 0, false);
10263 return DAG.getFrameIndex(FI, VT);
10264}
10265
10266SDValue ARMTargetLowering::LowerFP_TO_BF16(SDValue Op,
10267 SelectionDAG &DAG) const {
10268 SDLoc DL(Op);
10269 MakeLibCallOptions CallOptions;
10270 MVT SVT = Op.getOperand(0).getSimpleValueType();
10271 RTLIB::Libcall LC = RTLIB::getFPROUND(SVT, MVT::bf16);
10272 SDValue Res =
10273 makeLibCall(DAG, LC, MVT::f32, Op.getOperand(0), CallOptions, DL).first;
10274 return DAG.getBitcast(MVT::i32, Res);
10275}
10276
10277SDValue ARMTargetLowering::LowerCMP(SDValue Op, SelectionDAG &DAG) const {
10278 SDLoc dl(Op);
10279 SDValue LHS = Op.getOperand(0);
10280 SDValue RHS = Op.getOperand(1);
10281
10282 // Determine if this is signed or unsigned comparison
10283 bool IsSigned = (Op.getOpcode() == ISD::SCMP);
10284
10285 // Special case for Thumb1 UCMP only
10286 if (!IsSigned && Subtarget->isThumb1Only()) {
10287 // For Thumb unsigned comparison, use this sequence:
10288 // subs r2, r0, r1 ; r2 = LHS - RHS, sets flags
10289 // sbc r2, r2 ; r2 = r2 - r2 - !carry
10290 // cmp r1, r0 ; compare RHS with LHS
10291 // sbc r1, r1 ; r1 = r1 - r1 - !carry
10292 // subs r0, r2, r1 ; r0 = r2 - r1 (final result)
10293
10294 // First subtraction: LHS - RHS
10295 SDValue Sub1WithFlags = DAG.getNode(
10296 ARMISD::SUBC, dl, DAG.getVTList(MVT::i32, FlagsVT), LHS, RHS);
10297 SDValue Sub1Result = Sub1WithFlags.getValue(0);
10298 SDValue Flags1 = Sub1WithFlags.getValue(1);
10299
10300 // SUBE: Sub1Result - Sub1Result - !carry
10301 // This gives 0 if LHS >= RHS (unsigned), -1 if LHS < RHS (unsigned)
10302 SDValue Sbc1 =
10303 DAG.getNode(ARMISD::SUBE, dl, DAG.getVTList(MVT::i32, FlagsVT),
10304 Sub1Result, Sub1Result, Flags1);
10305 SDValue Sbc1Result = Sbc1.getValue(0);
10306
10307 // Second comparison: RHS vs LHS (reverse comparison)
10308 SDValue CmpFlags = DAG.getNode(ARMISD::CMP, dl, FlagsVT, RHS, LHS);
10309
10310 // SUBE: RHS - RHS - !carry
10311 // This gives 0 if RHS <= LHS (unsigned), -1 if RHS > LHS (unsigned)
10312 SDValue Sbc2 = DAG.getNode(
10313 ARMISD::SUBE, dl, DAG.getVTList(MVT::i32, FlagsVT), RHS, RHS, CmpFlags);
10314 SDValue Sbc2Result = Sbc2.getValue(0);
10315
10316 // Final subtraction: Sbc1Result - Sbc2Result (no flags needed)
10317 SDValue Result =
10318 DAG.getNode(ISD::SUB, dl, MVT::i32, Sbc1Result, Sbc2Result);
10319 if (Op.getValueType() != MVT::i32)
10320 Result = DAG.getSExtOrTrunc(Result, dl, Op.getValueType());
10321
10322 return Result;
10323 }
10324
10325 // For the ARM assembly pattern:
10326 // subs r0, r0, r1 ; subtract RHS from LHS and set flags
10327 // movgt r0, #1 ; if LHS > RHS, set result to 1 (GT for signed, HI for
10328 // unsigned) mvnlt r0, #0 ; if LHS < RHS, set result to -1 (LT for
10329 // signed, LO for unsigned)
10330 // ; if LHS == RHS, result remains 0 from the subs
10331
10332 // Optimization: if RHS is a subtraction against 0, use ADDC instead of SUBC
10333 unsigned Opcode = ARMISD::SUBC;
10334
10335 // Check if RHS is a subtraction against 0: (0 - X)
10336 if (RHS.getOpcode() == ISD::SUB) {
10337 SDValue SubLHS = RHS.getOperand(0);
10338 SDValue SubRHS = RHS.getOperand(1);
10339
10340 // Check if it's 0 - X
10341 if (isNullConstant(SubLHS)) {
10342 bool CanUseAdd = false;
10343 if (IsSigned) {
10344 // For SCMP: only if X is known to never be INT_MIN (to avoid overflow)
10345 if (RHS->getFlags().hasNoSignedWrap() || !DAG.computeKnownBits(SubRHS)
10347 .isMinSignedValue()) {
10348 CanUseAdd = true;
10349 }
10350 } else {
10351 // For UCMP: only if X is known to never be zero
10352 if (DAG.isKnownNeverZero(SubRHS)) {
10353 CanUseAdd = true;
10354 }
10355 }
10356
10357 if (CanUseAdd) {
10358 Opcode = ARMISD::ADDC;
10359 RHS = SubRHS; // Replace RHS with X, so we do LHS + X instead of
10360 // LHS - (0 - X)
10361 }
10362 }
10363 }
10364
10365 // Generate the operation with flags
10366 SDValue OpWithFlags =
10367 DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, FlagsVT), LHS, RHS);
10368
10369 SDValue OpResult = OpWithFlags.getValue(0);
10370 SDValue Flags = OpWithFlags.getValue(1);
10371
10372 // Constants for conditional moves
10373 SDValue One = DAG.getConstant(1, dl, MVT::i32);
10374 SDValue MinusOne = DAG.getAllOnesConstant(dl, MVT::i32);
10375
10376 // Select condition codes based on signed vs unsigned
10377 ARMCC::CondCodes GTCond = IsSigned ? ARMCC::GT : ARMCC::HI;
10378 ARMCC::CondCodes LTCond = IsSigned ? ARMCC::LT : ARMCC::LO;
10379
10380 // First conditional move: if greater than, set to 1
10381 SDValue GTCondValue = DAG.getConstant(GTCond, dl, MVT::i32);
10382 SDValue Result1 = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, OpResult, One,
10383 GTCondValue, Flags);
10384
10385 // Second conditional move: if less than, set to -1
10386 SDValue LTCondValue = DAG.getConstant(LTCond, dl, MVT::i32);
10387 SDValue Result2 = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, Result1, MinusOne,
10388 LTCondValue, Flags);
10389
10390 if (Op.getValueType() != MVT::i32)
10391 Result2 = DAG.getSExtOrTrunc(Result2, dl, Op.getValueType());
10392
10393 return Result2;
10394}
10395
10397 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
10398 switch (Op.getOpcode()) {
10399 default: llvm_unreachable("Don't know how to custom lower this!");
10400 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
10401 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10402 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10403 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10404 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10405 case ISD::SELECT: return LowerSELECT(Op, DAG);
10406 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
10407 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10408 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
10409 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
10410 case ISD::VASTART: return LowerVASTART(Op, DAG);
10411 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
10412 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
10415 case ISD::SINT_TO_FP:
10416 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
10419 case ISD::FP_TO_SINT:
10420 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
10422 case ISD::FP_TO_UINT_SAT: return LowerFP_TO_INT_SAT(Op, DAG, Subtarget);
10423 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10424 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10425 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10426 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
10427 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
10428 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
10429 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
10430 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
10431 Subtarget);
10432 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
10433 case ISD::SHL:
10434 case ISD::SRL:
10435 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
10436 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
10437 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
10438 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
10439 case ISD::SRL_PARTS:
10440 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
10441 case ISD::CTTZ:
10442 case ISD::CTTZ_ZERO_POISON: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
10443 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
10444 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget);
10445 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG);
10446 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
10447 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
10448 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
10449 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
10450 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10451 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
10452 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
10453 case ISD::TRUNCATE: return LowerTruncate(Op.getNode(), DAG, Subtarget);
10454 case ISD::SIGN_EXTEND:
10455 case ISD::ZERO_EXTEND: return LowerVectorExtend(Op.getNode(), DAG, Subtarget);
10456 case ISD::GET_ROUNDING: return LowerGET_ROUNDING(Op, DAG);
10457 case ISD::SET_ROUNDING: return LowerSET_ROUNDING(Op, DAG);
10458 case ISD::SET_FPMODE:
10459 return LowerSET_FPMODE(Op, DAG);
10460 case ISD::RESET_FPMODE:
10461 return LowerRESET_FPMODE(Op, DAG);
10462 case ISD::MUL: return LowerMUL(Op, DAG);
10463 case ISD::SDIV:
10464 if (getTargetMachine().getTargetTriple().isOSWindows() &&
10465 !Op.getValueType().isVector())
10466 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
10467 return LowerSDIV(Op, DAG, Subtarget);
10468 case ISD::UDIV:
10469 if (getTargetMachine().getTargetTriple().isOSWindows() &&
10470 !Op.getValueType().isVector())
10471 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
10472 return LowerUDIV(Op, DAG, Subtarget);
10473 case ISD::UADDO_CARRY:
10474 return LowerADDSUBO_CARRY(Op, DAG, ARMISD::ADDE, false /*unsigned*/);
10475 case ISD::USUBO_CARRY:
10476 return LowerADDSUBO_CARRY(Op, DAG, ARMISD::SUBE, false /*unsigned*/);
10477 case ISD::SADDO_CARRY:
10478 return LowerADDSUBO_CARRY(Op, DAG, ARMISD::ADDE, true /*signed*/);
10479 case ISD::SSUBO_CARRY:
10480 return LowerADDSUBO_CARRY(Op, DAG, ARMISD::SUBE, true /*signed*/);
10481 case ISD::UADDO:
10482 case ISD::USUBO:
10483 case ISD::UMULO:
10484 case ISD::SADDO:
10485 case ISD::SSUBO:
10486 case ISD::SMULO:
10487 return LowerALUO(Op, DAG);
10488 case ISD::SADDSAT:
10489 case ISD::SSUBSAT:
10490 case ISD::UADDSAT:
10491 case ISD::USUBSAT:
10492 return LowerADDSUBSAT(Op, DAG, Subtarget);
10493 case ISD::LOAD: {
10494 auto *LD = cast<LoadSDNode>(Op);
10495 EVT MemVT = LD->getMemoryVT();
10496 if (Subtarget->hasMVEIntegerOps() &&
10497 (MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
10498 MemVT == MVT::v16i1))
10499 return LowerPredicateLoad(Op, DAG);
10500
10501 auto Pair = LowerAEABIUnalignedLoad(Op, DAG);
10502 if (Pair.first)
10503 return DAG.getMergeValues({Pair.first, Pair.second}, SDLoc(Pair.first));
10504 return SDValue();
10505 }
10506 case ISD::STORE:
10507 return LowerSTORE(Op, DAG, Subtarget);
10508 case ISD::MLOAD:
10509 return LowerMLOAD(Op, DAG);
10510 case ISD::VECREDUCE_MUL:
10511 case ISD::VECREDUCE_AND:
10512 case ISD::VECREDUCE_OR:
10513 case ISD::VECREDUCE_XOR:
10514 return LowerVecReduce(Op, DAG, Subtarget);
10519 return LowerVecReduceF(Op, DAG, Subtarget);
10524 return LowerVecReduceMinMax(Op, DAG, Subtarget);
10525 case ISD::SDIVREM:
10526 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
10528 if (getTargetMachine().getTargetTriple().isOSWindows())
10529 return LowerDYNAMIC_STACKALLOC(Op, DAG);
10530 llvm_unreachable("Don't know how to custom lower this!");
10532 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
10534 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
10535 case ISD::STRICT_FSETCC:
10536 case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG);
10537 case ISD::SPONENTRY:
10538 return LowerSPONENTRY(Op, DAG);
10539 case ISD::FP_TO_BF16:
10540 return LowerFP_TO_BF16(Op, DAG);
10541 case ARMISD::WIN__DBZCHK: return SDValue();
10542 case ISD::UCMP:
10543 case ISD::SCMP:
10544 return LowerCMP(Op, DAG);
10545 case ISD::ABS:
10546 return LowerABS(Op, DAG);
10547 case ISD::STRICT_LROUND:
10549 case ISD::STRICT_LRINT:
10550 case ISD::STRICT_LLRINT: {
10551 assert((Op.getOperand(1).getValueType() == MVT::f16 ||
10552 Op.getOperand(1).getValueType() == MVT::bf16) &&
10553 "Expected custom lowering of rounding operations only for f16");
10554 SDLoc DL(Op);
10555 SDValue Ext = DAG.getNode(ISD::STRICT_FP_EXTEND, DL, {MVT::f32, MVT::Other},
10556 {Op.getOperand(0), Op.getOperand(1)});
10557 return DAG.getNode(Op.getOpcode(), DL, {Op.getValueType(), MVT::Other},
10558 {Ext.getValue(1), Ext.getValue(0)});
10559 }
10560 }
10561}
10562
10564 SelectionDAG &DAG) {
10565 unsigned IntNo = N->getConstantOperandVal(0);
10566 unsigned Opc = 0;
10567 if (IntNo == Intrinsic::arm_smlald)
10568 Opc = ARMISD::SMLALD;
10569 else if (IntNo == Intrinsic::arm_smlaldx)
10570 Opc = ARMISD::SMLALDX;
10571 else if (IntNo == Intrinsic::arm_smlsld)
10572 Opc = ARMISD::SMLSLD;
10573 else if (IntNo == Intrinsic::arm_smlsldx)
10574 Opc = ARMISD::SMLSLDX;
10575 else
10576 return;
10577
10578 SDLoc dl(N);
10579 SDValue Lo, Hi;
10580 std::tie(Lo, Hi) = DAG.SplitScalar(N->getOperand(3), dl, MVT::i32, MVT::i32);
10581
10582 SDValue LongMul = DAG.getNode(Opc, dl,
10583 DAG.getVTList(MVT::i32, MVT::i32),
10584 N->getOperand(1), N->getOperand(2),
10585 Lo, Hi);
10586 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64,
10587 LongMul.getValue(0), LongMul.getValue(1)));
10588}
10589
10590/// ReplaceNodeResults - Replace the results of node with an illegal result
10591/// type with new values built out of custom code.
10594 SelectionDAG &DAG) const {
10595 SDValue Res;
10596 switch (N->getOpcode()) {
10597 default:
10598 llvm_unreachable("Don't know how to custom expand this!");
10599 case ISD::READ_REGISTER:
10601 break;
10602 case ISD::BITCAST:
10603 Res = ExpandBITCAST(N, DAG, Subtarget);
10604 break;
10605 case ISD::SRL:
10606 case ISD::SRA:
10607 case ISD::SHL:
10608 Res = Expand64BitShift(N, DAG, Subtarget);
10609 break;
10610 case ISD::SREM:
10611 case ISD::UREM:
10612 Res = LowerREM(N, DAG);
10613 break;
10614 case ISD::SDIVREM:
10615 case ISD::UDIVREM:
10616 Res = LowerDivRem(SDValue(N, 0), DAG);
10617 assert(Res.getNumOperands() == 2 && "DivRem needs two values");
10618 Results.push_back(Res.getValue(0));
10619 Results.push_back(Res.getValue(1));
10620 return;
10621 case ISD::SADDSAT:
10622 case ISD::SSUBSAT:
10623 case ISD::UADDSAT:
10624 case ISD::USUBSAT:
10625 Res = LowerADDSUBSAT(SDValue(N, 0), DAG, Subtarget);
10626 break;
10628 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
10629 return;
10630 case ISD::UDIV:
10631 case ISD::SDIV:
10632 assert(getTargetMachine().getTargetTriple().isOSWindows() &&
10633 "can only expand DIV on Windows");
10634 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
10635 Results);
10638 return;
10640 return ReplaceLongIntrinsic(N, Results, DAG);
10641 case ISD::LOAD:
10642 LowerLOAD(N, Results, DAG);
10643 break;
10644 case ISD::STORE:
10645 Res = LowerAEABIUnalignedStore(SDValue(N, 0), DAG);
10646 break;
10647 case ISD::TRUNCATE:
10648 Res = LowerTruncate(N, DAG, Subtarget);
10649 break;
10650 case ISD::SIGN_EXTEND:
10651 case ISD::ZERO_EXTEND:
10652 Res = LowerVectorExtend(N, DAG, Subtarget);
10653 break;
10656 Res = LowerFP_TO_INT_SAT(SDValue(N, 0), DAG, Subtarget);
10657 break;
10658 }
10659 if (Res.getNode())
10660 Results.push_back(Res);
10661}
10662
10663//===----------------------------------------------------------------------===//
10664// ARM Scheduler Hooks
10665//===----------------------------------------------------------------------===//
10666
10667/// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
10668/// registers the function context.
10669void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
10671 MachineBasicBlock *DispatchBB,
10672 int FI) const {
10673 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
10674 "ROPI/RWPI not currently supported with SjLj");
10675 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10676 DebugLoc dl = MI.getDebugLoc();
10677 MachineFunction *MF = MBB->getParent();
10681 const Function &F = MF->getFunction();
10682
10683 bool isThumb = Subtarget->isThumb();
10684 bool isThumb2 = Subtarget->isThumb2();
10685
10686 unsigned PCLabelId = AFI->createPICLabelUId();
10687 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
10689 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
10690 unsigned CPI = MCP->getConstantPoolIndex(CPV, Align(4));
10691
10692 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
10693 : &ARM::GPRRegClass;
10694
10695 // Grab constant pool and fixed stack memory operands.
10696 MachineMemOperand *CPMMO =
10699
10700 MachineMemOperand *FIMMOSt =
10703
10704 // Load the address of the dispatch MBB into the jump buffer.
10705 if (isThumb2) {
10706 // Incoming value: jbuf
10707 // ldr.n r5, LCPI1_1
10708 // orr r5, r5, #1
10709 // add r5, pc
10710 // str r5, [$jbuf, #+4] ; &jbuf[1]
10711 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10712 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
10714 .addMemOperand(CPMMO)
10716 // Set the low bit because of thumb mode.
10717 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10718 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
10719 .addReg(NewVReg1)
10720 .addImm(0x01)
10722 .add(condCodeOp());
10723 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10724 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
10725 .addReg(NewVReg2)
10726 .addImm(PCLabelId);
10727 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
10728 .addReg(NewVReg3)
10729 .addFrameIndex(FI)
10730 .addImm(36) // &jbuf[1] :: pc
10731 .addMemOperand(FIMMOSt)
10733 } else if (isThumb) {
10734 // Incoming value: jbuf
10735 // ldr.n r1, LCPI1_4
10736 // add r1, pc
10737 // mov r2, #1
10738 // orrs r1, r2
10739 // add r2, $jbuf, #+4 ; &jbuf[1]
10740 // str r1, [r2]
10741 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10742 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
10744 .addMemOperand(CPMMO)
10746 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10747 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
10748 .addReg(NewVReg1)
10749 .addImm(PCLabelId);
10750 // Set the low bit because of thumb mode.
10751 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10752 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
10753 .addReg(ARM::CPSR, RegState::Define)
10754 .addImm(1)
10756 Register NewVReg4 = MRI->createVirtualRegister(TRC);
10757 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
10758 .addReg(ARM::CPSR, RegState::Define)
10759 .addReg(NewVReg2)
10760 .addReg(NewVReg3)
10762 Register NewVReg5 = MRI->createVirtualRegister(TRC);
10763 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
10764 .addFrameIndex(FI)
10765 .addImm(36); // &jbuf[1] :: pc
10766 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
10767 .addReg(NewVReg4)
10768 .addReg(NewVReg5)
10769 .addImm(0)
10770 .addMemOperand(FIMMOSt)
10772 } else {
10773 // Incoming value: jbuf
10774 // ldr r1, LCPI1_1
10775 // add r1, pc, r1
10776 // str r1, [$jbuf, #+4] ; &jbuf[1]
10777 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10778 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
10780 .addImm(0)
10781 .addMemOperand(CPMMO)
10783 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10784 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
10785 .addReg(NewVReg1)
10786 .addImm(PCLabelId)
10788 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
10789 .addReg(NewVReg2)
10790 .addFrameIndex(FI)
10791 .addImm(36) // &jbuf[1] :: pc
10792 .addMemOperand(FIMMOSt)
10794 }
10795}
10796
10797void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
10798 MachineBasicBlock *MBB) const {
10799 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10800 DebugLoc dl = MI.getDebugLoc();
10801 MachineFunction *MF = MBB->getParent();
10802 MachineRegisterInfo *MRI = &MF->getRegInfo();
10803 MachineFrameInfo &MFI = MF->getFrameInfo();
10804 int FI = MFI.getFunctionContextIndex();
10805
10806 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
10807 : &ARM::GPRnopcRegClass;
10808
10809 // Get a mapping of the call site numbers to all of the landing pads they're
10810 // associated with.
10811 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
10812 unsigned MaxCSNum = 0;
10813 for (MachineBasicBlock &BB : *MF) {
10814 if (!BB.isEHPad())
10815 continue;
10816
10817 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
10818 // pad.
10819 for (MachineInstr &II : BB) {
10820 if (!II.isEHLabel())
10821 continue;
10822
10823 MCSymbol *Sym = II.getOperand(0).getMCSymbol();
10824 if (!MF->hasCallSiteLandingPad(Sym)) continue;
10825
10826 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
10827 for (unsigned Idx : CallSiteIdxs) {
10828 CallSiteNumToLPad[Idx].push_back(&BB);
10829 MaxCSNum = std::max(MaxCSNum, Idx);
10830 }
10831 break;
10832 }
10833 }
10834
10835 // Get an ordered list of the machine basic blocks for the jump table.
10836 std::vector<MachineBasicBlock*> LPadList;
10837 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
10838 LPadList.reserve(CallSiteNumToLPad.size());
10839 for (unsigned I = 1; I <= MaxCSNum; ++I) {
10840 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
10841 for (MachineBasicBlock *MBB : MBBList) {
10842 LPadList.push_back(MBB);
10843 InvokeBBs.insert_range(MBB->predecessors());
10844 }
10845 }
10846
10847 assert(!LPadList.empty() &&
10848 "No landing pad destinations for the dispatch jump table!");
10849
10850 // Create the jump table and associated information.
10851 MachineJumpTableInfo *JTI =
10852 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
10853 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
10854
10855 // Create the MBBs for the dispatch code.
10856
10857 // Shove the dispatch's address into the return slot in the function context.
10858 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
10859 DispatchBB->setIsEHPad();
10860
10861 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10862
10863 BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
10864 DispatchBB->addSuccessor(TrapBB);
10865
10866 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
10867 DispatchBB->addSuccessor(DispContBB);
10868
10869 // Insert and MBBs.
10870 MF->insert(MF->end(), DispatchBB);
10871 MF->insert(MF->end(), DispContBB);
10872 MF->insert(MF->end(), TrapBB);
10873
10874 // Insert code into the entry block that creates and registers the function
10875 // context.
10876 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
10877
10878 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
10881
10882 MachineInstrBuilder MIB;
10883 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
10884
10885 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
10886 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
10887
10888 // Add a register mask with no preserved registers. This results in all
10889 // registers being marked as clobbered. This can't work if the dispatch block
10890 // is in a Thumb1 function and is linked with ARM code which uses the FP
10891 // registers, as there is no way to preserve the FP registers in Thumb1 mode.
10893
10894 bool IsPositionIndependent = isPositionIndependent();
10895 unsigned NumLPads = LPadList.size();
10896 if (Subtarget->isThumb2()) {
10897 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10898 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
10899 .addFrameIndex(FI)
10900 .addImm(4)
10901 .addMemOperand(FIMMOLd)
10903
10904 if (NumLPads < 256) {
10905 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
10906 .addReg(NewVReg1)
10907 .addImm(LPadList.size())
10909 } else {
10910 Register VReg1 = MRI->createVirtualRegister(TRC);
10911 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
10912 .addImm(NumLPads & 0xFFFF)
10914
10915 unsigned VReg2 = VReg1;
10916 if ((NumLPads & 0xFFFF0000) != 0) {
10917 VReg2 = MRI->createVirtualRegister(TRC);
10918 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
10919 .addReg(VReg1)
10920 .addImm(NumLPads >> 16)
10922 }
10923
10924 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
10925 .addReg(NewVReg1)
10926 .addReg(VReg2)
10928 }
10929
10930 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
10931 .addMBB(TrapBB)
10933 .addReg(ARM::CPSR);
10934
10935 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10936 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
10937 .addJumpTableIndex(MJTI)
10939
10940 Register NewVReg4 = MRI->createVirtualRegister(TRC);
10941 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
10942 .addReg(NewVReg3)
10943 .addReg(NewVReg1)
10946 .add(condCodeOp());
10947
10948 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
10949 .addReg(NewVReg4)
10950 .addReg(NewVReg1)
10951 .addJumpTableIndex(MJTI);
10952 } else if (Subtarget->isThumb()) {
10953 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10954 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
10955 .addFrameIndex(FI)
10956 .addImm(1)
10957 .addMemOperand(FIMMOLd)
10959
10960 if (NumLPads < 256) {
10961 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
10962 .addReg(NewVReg1)
10963 .addImm(NumLPads)
10965 } else {
10966 MachineConstantPool *ConstantPool = MF->getConstantPool();
10967 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10968 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
10969
10970 // MachineConstantPool wants an explicit alignment.
10971 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10972 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10973
10974 Register VReg1 = MRI->createVirtualRegister(TRC);
10975 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
10976 .addReg(VReg1, RegState::Define)
10979 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
10980 .addReg(NewVReg1)
10981 .addReg(VReg1)
10983 }
10984
10985 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
10986 .addMBB(TrapBB)
10988 .addReg(ARM::CPSR);
10989
10990 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10991 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
10992 .addReg(ARM::CPSR, RegState::Define)
10993 .addReg(NewVReg1)
10994 .addImm(2)
10996
10997 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10998 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
10999 .addJumpTableIndex(MJTI)
11001
11002 Register NewVReg4 = MRI->createVirtualRegister(TRC);
11003 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
11004 .addReg(ARM::CPSR, RegState::Define)
11005 .addReg(NewVReg2)
11006 .addReg(NewVReg3)
11008
11009 MachineMemOperand *JTMMOLd =
11010 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
11012
11013 Register NewVReg5 = MRI->createVirtualRegister(TRC);
11014 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
11015 .addReg(NewVReg4)
11016 .addImm(0)
11017 .addMemOperand(JTMMOLd)
11019
11020 unsigned NewVReg6 = NewVReg5;
11021 if (IsPositionIndependent) {
11022 NewVReg6 = MRI->createVirtualRegister(TRC);
11023 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
11024 .addReg(ARM::CPSR, RegState::Define)
11025 .addReg(NewVReg5)
11026 .addReg(NewVReg3)
11028 }
11029
11030 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
11031 .addReg(NewVReg6)
11032 .addJumpTableIndex(MJTI);
11033 } else {
11034 Register NewVReg1 = MRI->createVirtualRegister(TRC);
11035 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
11036 .addFrameIndex(FI)
11037 .addImm(4)
11038 .addMemOperand(FIMMOLd)
11040
11041 if (NumLPads < 256) {
11042 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
11043 .addReg(NewVReg1)
11044 .addImm(NumLPads)
11046 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
11047 Register VReg1 = MRI->createVirtualRegister(TRC);
11048 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
11049 .addImm(NumLPads & 0xFFFF)
11051
11052 unsigned VReg2 = VReg1;
11053 if ((NumLPads & 0xFFFF0000) != 0) {
11054 VReg2 = MRI->createVirtualRegister(TRC);
11055 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
11056 .addReg(VReg1)
11057 .addImm(NumLPads >> 16)
11059 }
11060
11061 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
11062 .addReg(NewVReg1)
11063 .addReg(VReg2)
11065 } else {
11066 MachineConstantPool *ConstantPool = MF->getConstantPool();
11067 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
11068 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
11069
11070 // MachineConstantPool wants an explicit alignment.
11071 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
11072 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
11073
11074 Register VReg1 = MRI->createVirtualRegister(TRC);
11075 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
11076 .addReg(VReg1, RegState::Define)
11078 .addImm(0)
11080 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
11081 .addReg(NewVReg1)
11082 .addReg(VReg1)
11084 }
11085
11086 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
11087 .addMBB(TrapBB)
11089 .addReg(ARM::CPSR);
11090
11091 Register NewVReg3 = MRI->createVirtualRegister(TRC);
11092 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
11093 .addReg(NewVReg1)
11096 .add(condCodeOp());
11097 Register NewVReg4 = MRI->createVirtualRegister(TRC);
11098 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
11099 .addJumpTableIndex(MJTI)
11101
11102 MachineMemOperand *JTMMOLd =
11103 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
11105 Register NewVReg5 = MRI->createVirtualRegister(TRC);
11106 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
11107 .addReg(NewVReg3)
11108 .addReg(NewVReg4)
11109 .addImm(0)
11110 .addMemOperand(JTMMOLd)
11112
11113 if (IsPositionIndependent) {
11114 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
11115 .addReg(NewVReg5)
11116 .addReg(NewVReg4)
11117 .addJumpTableIndex(MJTI);
11118 } else {
11119 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
11120 .addReg(NewVReg5)
11121 .addJumpTableIndex(MJTI);
11122 }
11123 }
11124
11125 // Add the jump table entries as successors to the MBB.
11126 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
11127 for (MachineBasicBlock *CurMBB : LPadList) {
11128 if (SeenMBBs.insert(CurMBB).second)
11129 DispContBB->addSuccessor(CurMBB);
11130 }
11131
11132 // N.B. the order the invoke BBs are processed in doesn't matter here.
11133 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
11135 for (MachineBasicBlock *BB : InvokeBBs) {
11136
11137 // Remove the landing pad successor from the invoke block and replace it
11138 // with the new dispatch block.
11139 SmallVector<MachineBasicBlock*, 4> Successors(BB->successors());
11140 while (!Successors.empty()) {
11141 MachineBasicBlock *SMBB = Successors.pop_back_val();
11142 if (SMBB->isEHPad()) {
11143 BB->removeSuccessor(SMBB);
11144 MBBLPads.push_back(SMBB);
11145 }
11146 }
11147
11148 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
11149 BB->normalizeSuccProbs();
11150
11151 // Find the invoke call and mark all of the callee-saved registers as
11152 // 'implicit defined' so that they're spilled. This prevents code from
11153 // moving instructions to before the EH block, where they will never be
11154 // executed.
11156 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
11157 if (!II->isCall()) continue;
11158
11159 DenseSet<unsigned> DefRegs;
11161 OI = II->operands_begin(), OE = II->operands_end();
11162 OI != OE; ++OI) {
11163 if (!OI->isReg()) continue;
11164 DefRegs.insert(OI->getReg());
11165 }
11166
11167 MachineInstrBuilder MIB(*MF, &*II);
11168
11169 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
11170 unsigned Reg = SavedRegs[i];
11171 if (Subtarget->isThumb2() &&
11172 !ARM::tGPRRegClass.contains(Reg) &&
11173 !ARM::hGPRRegClass.contains(Reg))
11174 continue;
11175 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
11176 continue;
11177 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
11178 continue;
11179 if (!DefRegs.contains(Reg))
11181 }
11182
11183 break;
11184 }
11185 }
11186
11187 // Mark all former landing pads as non-landing pads. The dispatch is the only
11188 // landing pad now.
11189 for (MachineBasicBlock *MBBLPad : MBBLPads)
11190 MBBLPad->setIsEHPad(false);
11191
11192 // The instruction is gone now.
11193 MI.eraseFromParent();
11194}
11195
11196static
11198 for (MachineBasicBlock *S : MBB->successors())
11199 if (S != Succ)
11200 return S;
11201 llvm_unreachable("Expecting a BB with two successors!");
11202}
11203
11204/// Return the load opcode for a given load size. If load size >= 8,
11205/// neon opcode will be returned.
11206static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
11207 if (LdSize >= 8)
11208 return LdSize == 16 ? ARM::VLD1q32wb_fixed
11209 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
11210 if (IsThumb1)
11211 return LdSize == 4 ? ARM::tLDRi
11212 : LdSize == 2 ? ARM::tLDRHi
11213 : LdSize == 1 ? ARM::tLDRBi : 0;
11214 if (IsThumb2)
11215 return LdSize == 4 ? ARM::t2LDR_POST
11216 : LdSize == 2 ? ARM::t2LDRH_POST
11217 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
11218 return LdSize == 4 ? ARM::LDR_POST_IMM
11219 : LdSize == 2 ? ARM::LDRH_POST
11220 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
11221}
11222
11223/// Return the store opcode for a given store size. If store size >= 8,
11224/// neon opcode will be returned.
11225static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
11226 if (StSize >= 8)
11227 return StSize == 16 ? ARM::VST1q32wb_fixed
11228 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
11229 if (IsThumb1)
11230 return StSize == 4 ? ARM::tSTRi
11231 : StSize == 2 ? ARM::tSTRHi
11232 : StSize == 1 ? ARM::tSTRBi : 0;
11233 if (IsThumb2)
11234 return StSize == 4 ? ARM::t2STR_POST
11235 : StSize == 2 ? ARM::t2STRH_POST
11236 : StSize == 1 ? ARM::t2STRB_POST : 0;
11237 return StSize == 4 ? ARM::STR_POST_IMM
11238 : StSize == 2 ? ARM::STRH_POST
11239 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
11240}
11241
11242/// Emit a post-increment load operation with given size. The instructions
11243/// will be added to BB at Pos.
11245 const TargetInstrInfo *TII, const DebugLoc &dl,
11246 unsigned LdSize, unsigned Data, unsigned AddrIn,
11247 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
11248 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
11249 assert(LdOpc != 0 && "Should have a load opcode");
11250 if (LdSize >= 8) {
11251 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11252 .addReg(AddrOut, RegState::Define)
11253 .addReg(AddrIn)
11254 .addImm(0)
11256 } else if (IsThumb1) {
11257 // load + update AddrIn
11258 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11259 .addReg(AddrIn)
11260 .addImm(0)
11262 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
11263 .add(t1CondCodeOp())
11264 .addReg(AddrIn)
11265 .addImm(LdSize)
11267 } else if (IsThumb2) {
11268 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11269 .addReg(AddrOut, RegState::Define)
11270 .addReg(AddrIn)
11271 .addImm(LdSize)
11273 } else { // arm
11274 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11275 .addReg(AddrOut, RegState::Define)
11276 .addReg(AddrIn)
11277 .addReg(0)
11278 .addImm(LdSize)
11280 }
11281}
11282
11283/// Emit a post-increment store operation with given size. The instructions
11284/// will be added to BB at Pos.
11286 const TargetInstrInfo *TII, const DebugLoc &dl,
11287 unsigned StSize, unsigned Data, unsigned AddrIn,
11288 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
11289 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
11290 assert(StOpc != 0 && "Should have a store opcode");
11291 if (StSize >= 8) {
11292 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11293 .addReg(AddrIn)
11294 .addImm(0)
11295 .addReg(Data)
11297 } else if (IsThumb1) {
11298 // store + update AddrIn
11299 BuildMI(*BB, Pos, dl, TII->get(StOpc))
11300 .addReg(Data)
11301 .addReg(AddrIn)
11302 .addImm(0)
11304 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
11305 .add(t1CondCodeOp())
11306 .addReg(AddrIn)
11307 .addImm(StSize)
11309 } else if (IsThumb2) {
11310 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11311 .addReg(Data)
11312 .addReg(AddrIn)
11313 .addImm(StSize)
11315 } else { // arm
11316 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11317 .addReg(Data)
11318 .addReg(AddrIn)
11319 .addReg(0)
11320 .addImm(StSize)
11322 }
11323}
11324
11326ARMTargetLowering::EmitStructByval(MachineInstr &MI,
11327 MachineBasicBlock *BB) const {
11328 // This pseudo instruction has 3 operands: dst, src, size
11329 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
11330 // Otherwise, we will generate unrolled scalar copies.
11331 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11332 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11334
11335 Register dest = MI.getOperand(0).getReg();
11336 Register src = MI.getOperand(1).getReg();
11337 unsigned SizeVal = MI.getOperand(2).getImm();
11338 unsigned Alignment = MI.getOperand(3).getImm();
11339 DebugLoc dl = MI.getDebugLoc();
11340
11341 MachineFunction *MF = BB->getParent();
11342 MachineRegisterInfo &MRI = MF->getRegInfo();
11343 unsigned UnitSize = 0;
11344 const TargetRegisterClass *TRC = nullptr;
11345 const TargetRegisterClass *VecTRC = nullptr;
11346
11347 bool IsThumb1 = Subtarget->isThumb1Only();
11348 bool IsThumb2 = Subtarget->isThumb2();
11349 bool IsThumb = Subtarget->isThumb();
11350
11351 if (Alignment & 1) {
11352 UnitSize = 1;
11353 } else if (Alignment & 2) {
11354 UnitSize = 2;
11355 } else {
11356 // Check whether we can use NEON instructions.
11357 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
11358 Subtarget->hasNEON()) {
11359 if ((Alignment % 16 == 0) && SizeVal >= 16)
11360 UnitSize = 16;
11361 else if ((Alignment % 8 == 0) && SizeVal >= 8)
11362 UnitSize = 8;
11363 }
11364 // Can't use NEON instructions.
11365 if (UnitSize == 0)
11366 UnitSize = 4;
11367 }
11368
11369 // Select the correct opcode and register class for unit size load/store
11370 bool IsNeon = UnitSize >= 8;
11371 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
11372 if (IsNeon)
11373 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
11374 : UnitSize == 8 ? &ARM::DPRRegClass
11375 : nullptr;
11376
11377 unsigned BytesLeft = SizeVal % UnitSize;
11378 unsigned LoopSize = SizeVal - BytesLeft;
11379
11380 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
11381 // Use LDR and STR to copy.
11382 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
11383 // [destOut] = STR_POST(scratch, destIn, UnitSize)
11384 unsigned srcIn = src;
11385 unsigned destIn = dest;
11386 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
11387 Register srcOut = MRI.createVirtualRegister(TRC);
11388 Register destOut = MRI.createVirtualRegister(TRC);
11389 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
11390 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
11391 IsThumb1, IsThumb2);
11392 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
11393 IsThumb1, IsThumb2);
11394 srcIn = srcOut;
11395 destIn = destOut;
11396 }
11397
11398 // Handle the leftover bytes with LDRB and STRB.
11399 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
11400 // [destOut] = STRB_POST(scratch, destIn, 1)
11401 for (unsigned i = 0; i < BytesLeft; i++) {
11402 Register srcOut = MRI.createVirtualRegister(TRC);
11403 Register destOut = MRI.createVirtualRegister(TRC);
11404 Register scratch = MRI.createVirtualRegister(TRC);
11405 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
11406 IsThumb1, IsThumb2);
11407 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
11408 IsThumb1, IsThumb2);
11409 srcIn = srcOut;
11410 destIn = destOut;
11411 }
11412 MI.eraseFromParent(); // The instruction is gone now.
11413 return BB;
11414 }
11415
11416 // Expand the pseudo op to a loop.
11417 // thisMBB:
11418 // ...
11419 // movw varEnd, # --> with thumb2
11420 // movt varEnd, #
11421 // ldrcp varEnd, idx --> without thumb2
11422 // fallthrough --> loopMBB
11423 // loopMBB:
11424 // PHI varPhi, varEnd, varLoop
11425 // PHI srcPhi, src, srcLoop
11426 // PHI destPhi, dst, destLoop
11427 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
11428 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
11429 // subs varLoop, varPhi, #UnitSize
11430 // bne loopMBB
11431 // fallthrough --> exitMBB
11432 // exitMBB:
11433 // epilogue to handle left-over bytes
11434 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
11435 // [destOut] = STRB_POST(scratch, destLoop, 1)
11436 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11437 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11438 MF->insert(It, loopMBB);
11439 MF->insert(It, exitMBB);
11440
11441 // Set the call frame size on entry to the new basic blocks.
11442 unsigned CallFrameSize = TII->getCallFrameSizeAt(MI);
11443 loopMBB->setCallFrameSize(CallFrameSize);
11444 exitMBB->setCallFrameSize(CallFrameSize);
11445
11446 // Transfer the remainder of BB and its successor edges to exitMBB.
11447 exitMBB->splice(exitMBB->begin(), BB,
11448 std::next(MachineBasicBlock::iterator(MI)), BB->end());
11450
11451 // Load an immediate to varEnd.
11452 Register varEnd = MRI.createVirtualRegister(TRC);
11453 if (Subtarget->useMovt()) {
11454 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi32imm : ARM::MOVi32imm),
11455 varEnd)
11456 .addImm(LoopSize);
11457 } else if (Subtarget->genExecuteOnly()) {
11458 assert(IsThumb && "Non-thumb expected to have used movt");
11459 BuildMI(BB, dl, TII->get(ARM::tMOVi32imm), varEnd).addImm(LoopSize);
11460 } else {
11461 MachineConstantPool *ConstantPool = MF->getConstantPool();
11462 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
11463 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
11464
11465 // MachineConstantPool wants an explicit alignment.
11467 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
11468 MachineMemOperand *CPMMO =
11471
11472 if (IsThumb)
11473 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
11474 .addReg(varEnd, RegState::Define)
11477 .addMemOperand(CPMMO);
11478 else
11479 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
11480 .addReg(varEnd, RegState::Define)
11482 .addImm(0)
11484 .addMemOperand(CPMMO);
11485 }
11486 BB->addSuccessor(loopMBB);
11487
11488 // Generate the loop body:
11489 // varPhi = PHI(varLoop, varEnd)
11490 // srcPhi = PHI(srcLoop, src)
11491 // destPhi = PHI(destLoop, dst)
11492 MachineBasicBlock *entryBB = BB;
11493 BB = loopMBB;
11494 Register varLoop = MRI.createVirtualRegister(TRC);
11495 Register varPhi = MRI.createVirtualRegister(TRC);
11496 Register srcLoop = MRI.createVirtualRegister(TRC);
11497 Register srcPhi = MRI.createVirtualRegister(TRC);
11498 Register destLoop = MRI.createVirtualRegister(TRC);
11499 Register destPhi = MRI.createVirtualRegister(TRC);
11500
11501 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
11502 .addReg(varLoop).addMBB(loopMBB)
11503 .addReg(varEnd).addMBB(entryBB);
11504 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
11505 .addReg(srcLoop).addMBB(loopMBB)
11506 .addReg(src).addMBB(entryBB);
11507 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
11508 .addReg(destLoop).addMBB(loopMBB)
11509 .addReg(dest).addMBB(entryBB);
11510
11511 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
11512 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
11513 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
11514 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
11515 IsThumb1, IsThumb2);
11516 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
11517 IsThumb1, IsThumb2);
11518
11519 // Decrement loop variable by UnitSize.
11520 if (IsThumb1) {
11521 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
11522 .add(t1CondCodeOp())
11523 .addReg(varPhi)
11524 .addImm(UnitSize)
11526 } else {
11527 MachineInstrBuilder MIB =
11528 BuildMI(*BB, BB->end(), dl,
11529 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
11530 MIB.addReg(varPhi)
11531 .addImm(UnitSize)
11533 .add(condCodeOp());
11534 MIB->getOperand(5).setReg(ARM::CPSR);
11535 MIB->getOperand(5).setIsDef(true);
11536 }
11537 BuildMI(*BB, BB->end(), dl,
11538 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
11539 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
11540
11541 // loopMBB can loop back to loopMBB or fall through to exitMBB.
11542 BB->addSuccessor(loopMBB);
11543 BB->addSuccessor(exitMBB);
11544
11545 // Add epilogue to handle BytesLeft.
11546 BB = exitMBB;
11547 auto StartOfExit = exitMBB->begin();
11548
11549 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
11550 // [destOut] = STRB_POST(scratch, destLoop, 1)
11551 unsigned srcIn = srcLoop;
11552 unsigned destIn = destLoop;
11553 for (unsigned i = 0; i < BytesLeft; i++) {
11554 Register srcOut = MRI.createVirtualRegister(TRC);
11555 Register destOut = MRI.createVirtualRegister(TRC);
11556 Register scratch = MRI.createVirtualRegister(TRC);
11557 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
11558 IsThumb1, IsThumb2);
11559 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
11560 IsThumb1, IsThumb2);
11561 srcIn = srcOut;
11562 destIn = destOut;
11563 }
11564
11565 MI.eraseFromParent(); // The instruction is gone now.
11566 return BB;
11567}
11568
11570ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
11571 MachineBasicBlock *MBB) const {
11572 const TargetMachine &TM = getTargetMachine();
11573 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
11574 DebugLoc DL = MI.getDebugLoc();
11575
11576 assert(TM.getTargetTriple().isOSWindows() &&
11577 "__chkstk is only supported on Windows");
11578 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
11579
11580 // __chkstk takes the number of words to allocate on the stack in R4, and
11581 // returns the stack adjustment in number of bytes in R4. This will not
11582 // clober any other registers (other than the obvious lr).
11583 //
11584 // Although, technically, IP should be considered a register which may be
11585 // clobbered, the call itself will not touch it. Windows on ARM is a pure
11586 // thumb-2 environment, so there is no interworking required. As a result, we
11587 // do not expect a veneer to be emitted by the linker, clobbering IP.
11588 //
11589 // Each module receives its own copy of __chkstk, so no import thunk is
11590 // required, again, ensuring that IP is not clobbered.
11591 //
11592 // Finally, although some linkers may theoretically provide a trampoline for
11593 // out of range calls (which is quite common due to a 32M range limitation of
11594 // branches for Thumb), we can generate the long-call version via
11595 // -mcmodel=large, alleviating the need for the trampoline which may clobber
11596 // IP.
11597
11598 RTLIB::LibcallImpl ChkStkLibcall = getLibcallImpl(RTLIB::STACK_PROBE);
11599 if (ChkStkLibcall == RTLIB::Unsupported)
11600 reportFatalUsageError("no available implementation of __chkstk");
11601
11602 const char *ChkStk = getLibcallImplName(ChkStkLibcall).data();
11603 switch (TM.getCodeModel()) {
11604 case CodeModel::Tiny:
11605 llvm_unreachable("Tiny code model not available on ARM.");
11606 case CodeModel::Small:
11607 case CodeModel::Medium:
11608 case CodeModel::Kernel:
11609 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
11611 .addExternalSymbol(ChkStk)
11612 .setOperandDead(3) // implicit-def $lr
11615 .addReg(ARM::R12,
11617 .addReg(ARM::CPSR,
11619 break;
11620 case CodeModel::Large: {
11621 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11622 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11623
11624 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
11625 .addExternalSymbol(ChkStk);
11628 .addReg(Reg)
11629 .setOperandDead(3) // implicit-def $lr
11632 .addReg(ARM::R12,
11634 .addReg(ARM::CPSR,
11636 break;
11637 }
11638 }
11639
11640 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
11641 .addReg(ARM::SP, RegState::Kill)
11642 .addReg(ARM::R4, RegState::Kill)
11645 .add(condCodeOp());
11646
11647 MI.eraseFromParent();
11648 return MBB;
11649}
11650
11652ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
11653 MachineBasicBlock *MBB) const {
11654 DebugLoc DL = MI.getDebugLoc();
11655 MachineFunction *MF = MBB->getParent();
11656 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11657
11658 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
11659 MF->insert(++MBB->getIterator(), ContBB);
11660 ContBB->splice(ContBB->begin(), MBB,
11661 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11663 MBB->addSuccessor(ContBB);
11664
11665 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
11666 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
11667 MF->push_back(TrapBB);
11668 MBB->addSuccessor(TrapBB);
11669
11670 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
11671 .addReg(MI.getOperand(0).getReg())
11672 .addImm(0)
11674 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
11675 .addMBB(TrapBB)
11677 .addReg(ARM::CPSR);
11678
11679 MI.eraseFromParent();
11680 return ContBB;
11681}
11682
11683// The CPSR operand of SelectItr might be missing a kill marker
11684// because there were multiple uses of CPSR, and ISel didn't know
11685// which to mark. Figure out whether SelectItr should have had a
11686// kill marker, and set it if it should. Returns the correct kill
11687// marker value.
11690 const TargetRegisterInfo* TRI) {
11691 // Scan forward through BB for a use/def of CPSR.
11692 MachineBasicBlock::iterator miI(std::next(SelectItr));
11693 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
11694 const MachineInstr& mi = *miI;
11695 if (mi.readsRegister(ARM::CPSR, /*TRI=*/nullptr))
11696 return false;
11697 if (mi.definesRegister(ARM::CPSR, /*TRI=*/nullptr))
11698 break; // Should have kill-flag - update below.
11699 }
11700
11701 // If we hit the end of the block, check whether CPSR is live into a
11702 // successor.
11703 if (miI == BB->end()) {
11704 for (MachineBasicBlock *Succ : BB->successors())
11705 if (Succ->isLiveIn(ARM::CPSR))
11706 return false;
11707 }
11708
11709 // We found a def, or hit the end of the basic block and CPSR wasn't live
11710 // out. SelectMI should have a kill flag on CPSR.
11711 SelectItr->addRegisterKilled(ARM::CPSR, TRI);
11712 return true;
11713}
11714
11715/// Adds logic in loop entry MBB to calculate loop iteration count and adds
11716/// t2WhileLoopSetup and t2WhileLoopStart to generate WLS loop
11718 MachineBasicBlock *TpLoopBody,
11719 MachineBasicBlock *TpExit, Register OpSizeReg,
11720 const TargetInstrInfo *TII, DebugLoc Dl,
11722 // Calculates loop iteration count = ceil(n/16) = (n + 15) >> 4.
11723 Register AddDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11724 BuildMI(TpEntry, Dl, TII->get(ARM::t2ADDri), AddDestReg)
11725 .addUse(OpSizeReg)
11726 .addImm(15)
11728 .addReg(0);
11729
11730 Register LsrDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11731 BuildMI(TpEntry, Dl, TII->get(ARM::t2LSRri), LsrDestReg)
11732 .addUse(AddDestReg)
11733 .addImm(4)
11735 .addReg(0);
11736
11737 Register TotalIterationsReg = MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11738 BuildMI(TpEntry, Dl, TII->get(ARM::t2WhileLoopSetup), TotalIterationsReg)
11739 .addUse(LsrDestReg);
11740
11741 BuildMI(TpEntry, Dl, TII->get(ARM::t2WhileLoopStart))
11742 .addUse(TotalIterationsReg)
11743 .addMBB(TpExit);
11744
11745 BuildMI(TpEntry, Dl, TII->get(ARM::t2B))
11746 .addMBB(TpLoopBody)
11748
11749 return TotalIterationsReg;
11750}
11751
11752/// Adds logic in the loopBody MBB to generate MVE_VCTP, t2DoLoopDec and
11753/// t2DoLoopEnd. These are used by later passes to generate tail predicated
11754/// loops.
11755static void genTPLoopBody(MachineBasicBlock *TpLoopBody,
11756 MachineBasicBlock *TpEntry, MachineBasicBlock *TpExit,
11757 const TargetInstrInfo *TII, DebugLoc Dl,
11758 MachineRegisterInfo &MRI, Register OpSrcReg,
11759 Register OpDestReg, Register ElementCountReg,
11760 Register TotalIterationsReg, bool IsMemcpy) {
11761 // First insert 4 PHI nodes for: Current pointer to Src (if memcpy), Dest
11762 // array, loop iteration counter, predication counter.
11763
11764 Register SrcPhiReg, CurrSrcReg;
11765 if (IsMemcpy) {
11766 // Current position in the src array
11767 SrcPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11768 CurrSrcReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11769 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), SrcPhiReg)
11770 .addUse(OpSrcReg)
11771 .addMBB(TpEntry)
11772 .addUse(CurrSrcReg)
11773 .addMBB(TpLoopBody);
11774 }
11775
11776 // Current position in the dest array
11777 Register DestPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11778 Register CurrDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11779 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), DestPhiReg)
11780 .addUse(OpDestReg)
11781 .addMBB(TpEntry)
11782 .addUse(CurrDestReg)
11783 .addMBB(TpLoopBody);
11784
11785 // Current loop counter
11786 Register LoopCounterPhiReg = MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11787 Register RemainingLoopIterationsReg =
11788 MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11789 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), LoopCounterPhiReg)
11790 .addUse(TotalIterationsReg)
11791 .addMBB(TpEntry)
11792 .addUse(RemainingLoopIterationsReg)
11793 .addMBB(TpLoopBody);
11794
11795 // Predication counter
11796 Register PredCounterPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11797 Register RemainingElementsReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11798 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), PredCounterPhiReg)
11799 .addUse(ElementCountReg)
11800 .addMBB(TpEntry)
11801 .addUse(RemainingElementsReg)
11802 .addMBB(TpLoopBody);
11803
11804 // Pass predication counter to VCTP
11805 Register VccrReg = MRI.createVirtualRegister(&ARM::VCCRRegClass);
11806 BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VCTP8), VccrReg)
11807 .addUse(PredCounterPhiReg)
11809 .addReg(0)
11810 .addReg(0);
11811
11812 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2SUBri), RemainingElementsReg)
11813 .addUse(PredCounterPhiReg)
11814 .addImm(16)
11816 .addReg(0);
11817
11818 // VLDRB (only if memcpy) and VSTRB instructions, predicated using VPR
11819 Register SrcValueReg;
11820 if (IsMemcpy) {
11821 SrcValueReg = MRI.createVirtualRegister(&ARM::MQPRRegClass);
11822 BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VLDRBU8_post))
11823 .addDef(CurrSrcReg)
11824 .addDef(SrcValueReg)
11825 .addReg(SrcPhiReg)
11826 .addImm(16)
11828 .addUse(VccrReg)
11829 .addReg(0);
11830 } else
11831 SrcValueReg = OpSrcReg;
11832
11833 BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VSTRBU8_post))
11834 .addDef(CurrDestReg)
11835 .addUse(SrcValueReg)
11836 .addReg(DestPhiReg)
11837 .addImm(16)
11839 .addUse(VccrReg)
11840 .addReg(0);
11841
11842 // Add the pseudoInstrs for decrementing the loop counter and marking the
11843 // end:t2DoLoopDec and t2DoLoopEnd
11844 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2LoopDec), RemainingLoopIterationsReg)
11845 .addUse(LoopCounterPhiReg)
11846 .addImm(1);
11847
11848 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2LoopEnd))
11849 .addUse(RemainingLoopIterationsReg)
11850 .addMBB(TpLoopBody);
11851
11852 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2B))
11853 .addMBB(TpExit)
11855}
11856
11858 // KCFI is supported in all ARM/Thumb modes
11859 return true;
11860}
11861
11865 const TargetInstrInfo *TII) const {
11866 assert(MBBI->isCall() && MBBI->getCFIType() &&
11867 "Invalid call instruction for a KCFI check");
11868
11869 MachineOperand *TargetOp = nullptr;
11870 switch (MBBI->getOpcode()) {
11871 // ARM mode opcodes
11872 case ARM::BLX:
11873 case ARM::BLX_pred:
11874 case ARM::BLX_noip:
11875 case ARM::BLX_pred_noip:
11876 case ARM::BX_CALL:
11877 TargetOp = &MBBI->getOperand(0);
11878 break;
11879 case ARM::TCRETURNri:
11880 case ARM::TCRETURNrinotr12:
11881 case ARM::TAILJMPr:
11882 case ARM::TAILJMPr4:
11883 TargetOp = &MBBI->getOperand(0);
11884 break;
11885 // Thumb mode opcodes (Thumb1 and Thumb2)
11886 // Note: Most Thumb call instructions have predicate operands before the
11887 // target register Format: tBLXr pred, predreg, target_register, ...
11888 case ARM::tBLXr: // Thumb1/Thumb2: BLX register (requires V5T)
11889 case ARM::tBLXr_noip: // Thumb1/Thumb2: BLX register, no IP clobber
11890 case ARM::tBX_CALL: // Thumb1 only: BX call (push LR, BX)
11891 TargetOp = &MBBI->getOperand(2);
11892 break;
11893 // Tail call instructions don't have predicates, target is operand 0
11894 case ARM::tTAILJMPr: // Thumb1/Thumb2: Tail call via register
11895 TargetOp = &MBBI->getOperand(0);
11896 break;
11897 default:
11898 llvm_unreachable("Unexpected CFI call opcode");
11899 }
11900
11901 assert(TargetOp && TargetOp->isReg() && "Invalid target operand");
11902 TargetOp->setIsRenamable(false);
11903
11904 // Select the appropriate KCFI_CHECK variant based on the instruction set
11905 unsigned KCFICheckOpcode;
11906 if (Subtarget->isThumb()) {
11907 if (Subtarget->isThumb2()) {
11908 KCFICheckOpcode = ARM::KCFI_CHECK_Thumb2;
11909 } else {
11910 KCFICheckOpcode = ARM::KCFI_CHECK_Thumb1;
11911 }
11912 } else {
11913 KCFICheckOpcode = ARM::KCFI_CHECK_ARM;
11914 }
11915
11916 return BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(KCFICheckOpcode))
11917 .addReg(TargetOp->getReg())
11918 .addImm(MBBI->getCFIType())
11919 .getInstr();
11920}
11921
11924 MachineBasicBlock *BB) const {
11925 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11926 DebugLoc dl = MI.getDebugLoc();
11927 bool isThumb2 = Subtarget->isThumb2();
11928 switch (MI.getOpcode()) {
11929 default: {
11930 MI.print(errs());
11931 llvm_unreachable("Unexpected instr type to insert");
11932 }
11933
11934 // Thumb1 post-indexed loads are really just single-register LDMs.
11935 case ARM::tLDR_postidx: {
11936 MachineOperand Def(MI.getOperand(1));
11937 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
11938 .add(Def) // Rn_wb
11939 .add(MI.getOperand(2)) // Rn
11940 .add(MI.getOperand(3)) // PredImm
11941 .add(MI.getOperand(4)) // PredReg
11942 .add(MI.getOperand(0)) // Rt
11943 .cloneMemRefs(MI);
11944 MI.eraseFromParent();
11945 return BB;
11946 }
11947
11948 case ARM::MVE_MEMCPYLOOPINST:
11949 case ARM::MVE_MEMSETLOOPINST: {
11950
11951 // Transformation below expands MVE_MEMCPYLOOPINST/MVE_MEMSETLOOPINST Pseudo
11952 // into a Tail Predicated (TP) Loop. It adds the instructions to calculate
11953 // the iteration count =ceil(size_in_bytes/16)) in the TP entry block and
11954 // adds the relevant instructions in the TP loop Body for generation of a
11955 // WLSTP loop.
11956
11957 // Below is relevant portion of the CFG after the transformation.
11958 // The Machine Basic Blocks are shown along with branch conditions (in
11959 // brackets). Note that TP entry/exit MBBs depict the entry/exit of this
11960 // portion of the CFG and may not necessarily be the entry/exit of the
11961 // function.
11962
11963 // (Relevant) CFG after transformation:
11964 // TP entry MBB
11965 // |
11966 // |-----------------|
11967 // (n <= 0) (n > 0)
11968 // | |
11969 // | TP loop Body MBB<--|
11970 // | | |
11971 // \ |___________|
11972 // \ /
11973 // TP exit MBB
11974
11975 MachineFunction *MF = BB->getParent();
11976 MachineFunctionProperties &Properties = MF->getProperties();
11978
11979 Register OpDestReg = MI.getOperand(0).getReg();
11980 Register OpSrcReg = MI.getOperand(1).getReg();
11981 Register OpSizeReg = MI.getOperand(2).getReg();
11982
11983 // Allocate the required MBBs and add to parent function.
11984 MachineBasicBlock *TpEntry = BB;
11985 MachineBasicBlock *TpLoopBody = MF->CreateMachineBasicBlock();
11986 MachineBasicBlock *TpExit;
11987
11988 MF->push_back(TpLoopBody);
11989
11990 // If any instructions are present in the current block after
11991 // MVE_MEMCPYLOOPINST or MVE_MEMSETLOOPINST, split the current block and
11992 // move the instructions into the newly created exit block. If there are no
11993 // instructions add an explicit branch to the FallThrough block and then
11994 // split.
11995 //
11996 // The split is required for two reasons:
11997 // 1) A terminator(t2WhileLoopStart) will be placed at that site.
11998 // 2) Since a TPLoopBody will be added later, any phis in successive blocks
11999 // need to be updated. splitAt() already handles this.
12000 TpExit = BB->splitAt(MI, false);
12001 if (TpExit == BB) {
12002 assert(BB->canFallThrough() && "Exit Block must be Fallthrough of the "
12003 "block containing memcpy/memset Pseudo");
12004 TpExit = BB->getFallThrough();
12005 BuildMI(BB, dl, TII->get(ARM::t2B))
12006 .addMBB(TpExit)
12008 TpExit = BB->splitAt(MI, false);
12009 }
12010
12011 // Add logic for iteration count
12012 Register TotalIterationsReg =
12013 genTPEntry(TpEntry, TpLoopBody, TpExit, OpSizeReg, TII, dl, MRI);
12014
12015 // Add the vectorized (and predicated) loads/store instructions
12016 bool IsMemcpy = MI.getOpcode() == ARM::MVE_MEMCPYLOOPINST;
12017 genTPLoopBody(TpLoopBody, TpEntry, TpExit, TII, dl, MRI, OpSrcReg,
12018 OpDestReg, OpSizeReg, TotalIterationsReg, IsMemcpy);
12019
12020 // Required to avoid conflict with the MachineVerifier during testing.
12021 Properties.resetNoPHIs();
12022
12023 // Connect the blocks
12024 TpEntry->addSuccessor(TpLoopBody);
12025 TpLoopBody->addSuccessor(TpLoopBody);
12026 TpLoopBody->addSuccessor(TpExit);
12027
12028 // Reorder for a more natural layout
12029 TpLoopBody->moveAfter(TpEntry);
12030 TpExit->moveAfter(TpLoopBody);
12031
12032 // Finally, remove the memcpy Pseudo Instruction
12033 MI.eraseFromParent();
12034
12035 // Return the exit block as it may contain other instructions requiring a
12036 // custom inserter
12037 return TpExit;
12038 }
12039
12040 // The Thumb2 pre-indexed stores have the same MI operands, they just
12041 // define them differently in the .td files from the isel patterns, so
12042 // they need pseudos.
12043 case ARM::t2STR_preidx:
12044 MI.setDesc(TII->get(ARM::t2STR_PRE));
12045 return BB;
12046 case ARM::t2STRB_preidx:
12047 MI.setDesc(TII->get(ARM::t2STRB_PRE));
12048 return BB;
12049 case ARM::t2STRH_preidx:
12050 MI.setDesc(TII->get(ARM::t2STRH_PRE));
12051 return BB;
12052
12053 case ARM::STRi_preidx:
12054 case ARM::STRBi_preidx: {
12055 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
12056 : ARM::STRB_PRE_IMM;
12057 // Decode the offset.
12058 unsigned Offset = MI.getOperand(4).getImm();
12059 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
12061 if (isSub)
12062 Offset = -Offset;
12063
12064 MachineMemOperand *MMO = *MI.memoperands_begin();
12065 BuildMI(*BB, MI, dl, TII->get(NewOpc))
12066 .add(MI.getOperand(0)) // Rn_wb
12067 .add(MI.getOperand(1)) // Rt
12068 .add(MI.getOperand(2)) // Rn
12069 .addImm(Offset) // offset (skip GPR==zero_reg)
12070 .add(MI.getOperand(5)) // pred
12071 .add(MI.getOperand(6))
12072 .addMemOperand(MMO);
12073 MI.eraseFromParent();
12074 return BB;
12075 }
12076 case ARM::STRr_preidx:
12077 case ARM::STRBr_preidx:
12078 case ARM::STRH_preidx: {
12079 unsigned NewOpc;
12080 switch (MI.getOpcode()) {
12081 default: llvm_unreachable("unexpected opcode!");
12082 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
12083 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
12084 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
12085 }
12086 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
12087 for (const MachineOperand &MO : MI.operands())
12088 MIB.add(MO);
12089 MI.eraseFromParent();
12090 return BB;
12091 }
12092
12093 case ARM::tMOVCCr_pseudo: {
12094 // To "insert" a SELECT_CC instruction, we actually have to insert the
12095 // diamond control-flow pattern. The incoming instruction knows the
12096 // destination vreg to set, the condition code register to branch on, the
12097 // true/false values to select between, and a branch opcode to use.
12098 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12100
12101 // thisMBB:
12102 // ...
12103 // TrueVal = ...
12104 // cmpTY ccX, r1, r2
12105 // bCC copy1MBB
12106 // fallthrough --> copy0MBB
12107 MachineBasicBlock *thisMBB = BB;
12108 MachineFunction *F = BB->getParent();
12109 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12110 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12111 F->insert(It, copy0MBB);
12112 F->insert(It, sinkMBB);
12113
12114 // Set the call frame size on entry to the new basic blocks.
12115 unsigned CallFrameSize = TII->getCallFrameSizeAt(MI);
12116 copy0MBB->setCallFrameSize(CallFrameSize);
12117 sinkMBB->setCallFrameSize(CallFrameSize);
12118
12119 // Check whether CPSR is live past the tMOVCCr_pseudo.
12120 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
12121 if (!MI.killsRegister(ARM::CPSR, /*TRI=*/nullptr) &&
12122 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
12123 copy0MBB->addLiveIn(ARM::CPSR);
12124 sinkMBB->addLiveIn(ARM::CPSR);
12125 }
12126
12127 // Transfer the remainder of BB and its successor edges to sinkMBB.
12128 sinkMBB->splice(sinkMBB->begin(), BB,
12129 std::next(MachineBasicBlock::iterator(MI)), BB->end());
12131
12132 BB->addSuccessor(copy0MBB);
12133 BB->addSuccessor(sinkMBB);
12134
12135 BuildMI(BB, dl, TII->get(ARM::tBcc))
12136 .addMBB(sinkMBB)
12137 .addImm(MI.getOperand(3).getImm())
12138 .addReg(MI.getOperand(4).getReg());
12139
12140 // copy0MBB:
12141 // %FalseValue = ...
12142 // # fallthrough to sinkMBB
12143 BB = copy0MBB;
12144
12145 // Update machine-CFG edges
12146 BB->addSuccessor(sinkMBB);
12147
12148 // sinkMBB:
12149 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12150 // ...
12151 BB = sinkMBB;
12152 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
12153 .addReg(MI.getOperand(1).getReg())
12154 .addMBB(copy0MBB)
12155 .addReg(MI.getOperand(2).getReg())
12156 .addMBB(thisMBB);
12157
12158 MI.eraseFromParent(); // The pseudo instruction is gone now.
12159 return BB;
12160 }
12161
12162 case ARM::BCCi64:
12163 case ARM::BCCZi64: {
12164 // If there is an unconditional branch to the other successor, remove it.
12165 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
12166
12167 // Compare both parts that make up the double comparison separately for
12168 // equality.
12169 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
12170
12171 Register LHS1 = MI.getOperand(1).getReg();
12172 Register LHS2 = MI.getOperand(2).getReg();
12173 if (RHSisZero) {
12174 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
12175 .addReg(LHS1)
12176 .addImm(0)
12178 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
12179 .addReg(LHS2).addImm(0)
12180 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
12181 } else {
12182 Register RHS1 = MI.getOperand(3).getReg();
12183 Register RHS2 = MI.getOperand(4).getReg();
12184 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
12185 .addReg(LHS1)
12186 .addReg(RHS1)
12188 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
12189 .addReg(LHS2).addReg(RHS2)
12190 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
12191 }
12192
12193 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
12194 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
12195 if (MI.getOperand(0).getImm() == ARMCC::NE)
12196 std::swap(destMBB, exitMBB);
12197
12198 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
12199 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
12200 if (isThumb2)
12201 BuildMI(BB, dl, TII->get(ARM::t2B))
12202 .addMBB(exitMBB)
12204 else
12205 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
12206
12207 MI.eraseFromParent(); // The pseudo instruction is gone now.
12208 return BB;
12209 }
12210
12211 case ARM::Int_eh_sjlj_setjmp:
12212 case ARM::Int_eh_sjlj_setjmp_nofp:
12213 case ARM::tInt_eh_sjlj_setjmp:
12214 case ARM::t2Int_eh_sjlj_setjmp:
12215 case ARM::t2Int_eh_sjlj_setjmp_nofp:
12216 return BB;
12217
12218 case ARM::Int_eh_sjlj_setup_dispatch:
12219 EmitSjLjDispatchBlock(MI, BB);
12220 return BB;
12221 case ARM::COPY_STRUCT_BYVAL_I32:
12222 ++NumLoopByVals;
12223 return EmitStructByval(MI, BB);
12224 case ARM::WIN__CHKSTK:
12225 return EmitLowered__chkstk(MI, BB);
12226 case ARM::WIN__DBZCHK:
12227 return EmitLowered__dbzchk(MI, BB);
12228 }
12229}
12230
12231/// Attaches vregs to MEMCPY that it will use as scratch registers
12232/// when it is expanded into LDM/STM. This is done as a post-isel lowering
12233/// instead of as a custom inserter because we need the use list from the SDNode.
12235 MachineInstr &MI, const SDNode *Node) {
12236 bool isThumb1 = Subtarget->isThumb1Only();
12237
12238 MachineFunction *MF = MI.getParent()->getParent();
12240 MachineInstrBuilder MIB(*MF, MI);
12241
12242 // If the new dst/src is unused mark it as dead.
12243 if (!Node->hasAnyUseOfValue(0)) {
12244 MI.getOperand(0).setIsDead(true);
12245 }
12246 if (!Node->hasAnyUseOfValue(1)) {
12247 MI.getOperand(1).setIsDead(true);
12248 }
12249
12250 // The MEMCPY both defines and kills the scratch registers.
12251 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
12252 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
12253 : &ARM::GPRRegClass);
12255 }
12256}
12257
12259 SDNode *Node) const {
12260 if (MI.getOpcode() == ARM::MEMCPY) {
12261 attachMEMCPYScratchRegs(Subtarget, MI, Node);
12262 return;
12263 }
12264
12265 const MCInstrDesc *MCID = &MI.getDesc();
12266 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
12267 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
12268 // operand is still set to noreg. If needed, set the optional operand's
12269 // register to CPSR, and remove the redundant implicit def.
12270 //
12271 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
12272
12273 // Rename pseudo opcodes.
12274 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
12275 unsigned ccOutIdx;
12276 if (NewOpc) {
12277 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
12278 MCID = &TII->get(NewOpc);
12279
12280 assert(MCID->getNumOperands() ==
12281 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
12282 && "converted opcode should be the same except for cc_out"
12283 " (and, on Thumb1, pred)");
12284
12285 MI.setDesc(*MCID);
12286
12287 // Add the optional cc_out operand
12288 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
12289
12290 // On Thumb1, move all input operands to the end, then add the predicate
12291 if (Subtarget->isThumb1Only()) {
12292 for (unsigned c = MCID->getNumOperands() - 4; c--;) {
12293 MI.addOperand(MI.getOperand(1));
12294 MI.removeOperand(1);
12295 }
12296
12297 // Restore the ties
12298 for (unsigned i = MI.getNumOperands(); i--;) {
12299 const MachineOperand& op = MI.getOperand(i);
12300 if (op.isReg() && op.isUse()) {
12301 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
12302 if (DefIdx != -1)
12303 MI.tieOperands(DefIdx, i);
12304 }
12305 }
12306
12308 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
12309 ccOutIdx = 1;
12310 } else
12311 ccOutIdx = MCID->getNumOperands() - 1;
12312 } else
12313 ccOutIdx = MCID->getNumOperands() - 1;
12314
12315 // Any ARM instruction that sets the 's' bit should specify an optional
12316 // "cc_out" operand in the last operand position.
12317 if (!MI.hasOptionalDef() || !MCID->operands()[ccOutIdx].isOptionalDef()) {
12318 assert(!NewOpc && "Optional cc_out operand required");
12319 return;
12320 }
12321 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
12322 // since we already have an optional CPSR def.
12323 bool definesCPSR = false;
12324 bool deadCPSR = false;
12325 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
12326 ++i) {
12327 const MachineOperand &MO = MI.getOperand(i);
12328 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
12329 definesCPSR = true;
12330 if (MO.isDead())
12331 deadCPSR = true;
12332 MI.removeOperand(i);
12333 break;
12334 }
12335 }
12336 if (!definesCPSR) {
12337 assert(!NewOpc && "Optional cc_out operand required");
12338 return;
12339 }
12340 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
12341 if (deadCPSR) {
12342 assert(!MI.getOperand(ccOutIdx).getReg() &&
12343 "expect uninitialized optional cc_out operand");
12344 // Thumb1 instructions must have the S bit even if the CPSR is dead.
12345 if (!Subtarget->isThumb1Only())
12346 return;
12347 }
12348
12349 // If this instruction was defined with an optional CPSR def and its dag node
12350 // had a live implicit CPSR def, then activate the optional CPSR def.
12351 MachineOperand &MO = MI.getOperand(ccOutIdx);
12352 MO.setReg(ARM::CPSR);
12353 MO.setIsDef(true);
12354 MO.setIsDead(deadCPSR);
12355}
12356
12357//===----------------------------------------------------------------------===//
12358// ARM Optimization Hooks
12359//===----------------------------------------------------------------------===//
12360
12361// Helper function that checks if N is a null or all ones constant.
12362static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
12364}
12365
12366// Return true if N is conditionally 0 or all ones.
12367// Detects these expressions where cc is an i1 value:
12368//
12369// (select cc 0, y) [AllOnes=0]
12370// (select cc y, 0) [AllOnes=0]
12371// (zext cc) [AllOnes=0]
12372// (sext cc) [AllOnes=0/1]
12373// (select cc -1, y) [AllOnes=1]
12374// (select cc y, -1) [AllOnes=1]
12375//
12376// Invert is set when N is the null/all ones constant when CC is false.
12377// OtherOp is set to the alternative value of N.
12379 SDValue &CC, bool &Invert,
12380 SDValue &OtherOp,
12381 SelectionDAG &DAG) {
12382 switch (N->getOpcode()) {
12383 default: return false;
12384 case ISD::SELECT: {
12385 CC = N->getOperand(0);
12386 SDValue N1 = N->getOperand(1);
12387 SDValue N2 = N->getOperand(2);
12388 if (isZeroOrAllOnes(N1, AllOnes)) {
12389 Invert = false;
12390 OtherOp = N2;
12391 return true;
12392 }
12393 if (isZeroOrAllOnes(N2, AllOnes)) {
12394 Invert = true;
12395 OtherOp = N1;
12396 return true;
12397 }
12398 return false;
12399 }
12400 case ISD::ZERO_EXTEND:
12401 // (zext cc) can never be the all ones value.
12402 if (AllOnes)
12403 return false;
12404 [[fallthrough]];
12405 case ISD::SIGN_EXTEND: {
12406 SDLoc dl(N);
12407 EVT VT = N->getValueType(0);
12408 CC = N->getOperand(0);
12409 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
12410 return false;
12411 Invert = !AllOnes;
12412 if (AllOnes)
12413 // When looking for an AllOnes constant, N is an sext, and the 'other'
12414 // value is 0.
12415 OtherOp = DAG.getConstant(0, dl, VT);
12416 else if (N->getOpcode() == ISD::ZERO_EXTEND)
12417 // When looking for a 0 constant, N can be zext or sext.
12418 OtherOp = DAG.getConstant(1, dl, VT);
12419 else
12420 OtherOp = DAG.getAllOnesConstant(dl, VT);
12421 return true;
12422 }
12423 }
12424}
12425
12426// Combine a constant select operand into its use:
12427//
12428// (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
12429// (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
12430// (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
12431// (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
12432// (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
12433//
12434// The transform is rejected if the select doesn't have a constant operand that
12435// is null, or all ones when AllOnes is set.
12436//
12437// Also recognize sext/zext from i1:
12438//
12439// (add (zext cc), x) -> (select cc (add x, 1), x)
12440// (add (sext cc), x) -> (select cc (add x, -1), x)
12441//
12442// These transformations eventually create predicated instructions.
12443//
12444// @param N The node to transform.
12445// @param Slct The N operand that is a select.
12446// @param OtherOp The other N operand (x above).
12447// @param DCI Context.
12448// @param AllOnes Require the select constant to be all ones instead of null.
12449// @returns The new node, or SDValue() on failure.
12450static
12453 bool AllOnes = false) {
12454 SelectionDAG &DAG = DCI.DAG;
12455 EVT VT = N->getValueType(0);
12456 SDValue NonConstantVal;
12457 SDValue CCOp;
12458 bool SwapSelectOps;
12459 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
12460 NonConstantVal, DAG))
12461 return SDValue();
12462
12463 // Slct is now know to be the desired identity constant when CC is true.
12464 SDValue TrueVal = OtherOp;
12465 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12466 OtherOp, NonConstantVal);
12467 // Unless SwapSelectOps says CC should be false.
12468 if (SwapSelectOps)
12469 std::swap(TrueVal, FalseVal);
12470
12471 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
12472 CCOp, TrueVal, FalseVal);
12473}
12474
12475// Attempt combineSelectAndUse on each operand of a commutative operator N.
12476static
12479 SDValue N0 = N->getOperand(0);
12480 SDValue N1 = N->getOperand(1);
12481 if (N0.getNode()->hasOneUse())
12482 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
12483 return Result;
12484 if (N1.getNode()->hasOneUse())
12485 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
12486 return Result;
12487 return SDValue();
12488}
12489
12491 // VUZP shuffle node.
12492 if (N->getOpcode() == ARMISD::VUZP)
12493 return true;
12494
12495 // "VUZP" on i32 is an alias for VTRN.
12496 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
12497 return true;
12498
12499 return false;
12500}
12501
12504 const ARMSubtarget *Subtarget) {
12505 // Look for ADD(VUZP.0, VUZP.1).
12506 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
12507 N0 == N1)
12508 return SDValue();
12509
12510 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
12511 if (!N->getValueType(0).is64BitVector())
12512 return SDValue();
12513
12514 // Generate vpadd.
12515 SelectionDAG &DAG = DCI.DAG;
12517 SDLoc dl(N);
12518 SDNode *Unzip = N0.getNode();
12519 EVT VT = N->getValueType(0);
12520
12522 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
12523 TLI.getPointerTy(DAG.getDataLayout())));
12524 Ops.push_back(Unzip->getOperand(0));
12525 Ops.push_back(Unzip->getOperand(1));
12526
12527 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
12528}
12529
12532 const ARMSubtarget *Subtarget) {
12533 // Check for two extended operands.
12534 if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
12535 N1.getOpcode() == ISD::SIGN_EXTEND) &&
12536 !(N0.getOpcode() == ISD::ZERO_EXTEND &&
12537 N1.getOpcode() == ISD::ZERO_EXTEND))
12538 return SDValue();
12539
12540 SDValue N00 = N0.getOperand(0);
12541 SDValue N10 = N1.getOperand(0);
12542
12543 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
12544 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
12545 N00 == N10)
12546 return SDValue();
12547
12548 // We only recognize Q register paddl here; this can't be reached until
12549 // after type legalization.
12550 if (!N00.getValueType().is64BitVector() ||
12552 return SDValue();
12553
12554 // Generate vpaddl.
12555 SelectionDAG &DAG = DCI.DAG;
12557 SDLoc dl(N);
12558 EVT VT = N->getValueType(0);
12559
12561 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
12562 unsigned Opcode;
12563 if (N0.getOpcode() == ISD::SIGN_EXTEND)
12564 Opcode = Intrinsic::arm_neon_vpaddls;
12565 else
12566 Opcode = Intrinsic::arm_neon_vpaddlu;
12567 Ops.push_back(DAG.getConstant(Opcode, dl,
12568 TLI.getPointerTy(DAG.getDataLayout())));
12570 unsigned NumElts = VT.getVectorNumElements();
12571 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
12572 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
12573 N00.getOperand(0), N00.getOperand(1));
12574 Ops.push_back(Concat);
12575
12576 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
12577}
12578
12579// FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
12580// an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
12581// much easier to match.
12582static SDValue
12585 const ARMSubtarget *Subtarget) {
12586 // Only perform optimization if after legalize, and if NEON is available. We
12587 // also expected both operands to be BUILD_VECTORs.
12588 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
12589 || N0.getOpcode() != ISD::BUILD_VECTOR
12590 || N1.getOpcode() != ISD::BUILD_VECTOR)
12591 return SDValue();
12592
12593 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
12594 EVT VT = N->getValueType(0);
12595 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
12596 return SDValue();
12597
12598 // Check that the vector operands are of the right form.
12599 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
12600 // operands, where N is the size of the formed vector.
12601 // Each EXTRACT_VECTOR should have the same input vector and odd or even
12602 // index such that we have a pair wise add pattern.
12603
12604 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
12606 return SDValue();
12607 SDValue Vec = N0->getOperand(0)->getOperand(0);
12608 SDNode *V = Vec.getNode();
12609 unsigned nextIndex = 0;
12610
12611 // For each operands to the ADD which are BUILD_VECTORs,
12612 // check to see if each of their operands are an EXTRACT_VECTOR with
12613 // the same vector and appropriate index.
12614 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
12617
12618 SDValue ExtVec0 = N0->getOperand(i);
12619 SDValue ExtVec1 = N1->getOperand(i);
12620
12621 // First operand is the vector, verify its the same.
12622 if (V != ExtVec0->getOperand(0).getNode() ||
12623 V != ExtVec1->getOperand(0).getNode())
12624 return SDValue();
12625
12626 // Second is the constant, verify its correct.
12629
12630 // For the constant, we want to see all the even or all the odd.
12631 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
12632 || C1->getZExtValue() != nextIndex+1)
12633 return SDValue();
12634
12635 // Increment index.
12636 nextIndex+=2;
12637 } else
12638 return SDValue();
12639 }
12640
12641 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
12642 // we're using the entire input vector, otherwise there's a size/legality
12643 // mismatch somewhere.
12644 if (nextIndex != Vec.getValueType().getVectorNumElements() ||
12646 return SDValue();
12647
12648 // Create VPADDL node.
12649 SelectionDAG &DAG = DCI.DAG;
12651
12652 SDLoc dl(N);
12653
12654 // Build operand list.
12656 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
12657 TLI.getPointerTy(DAG.getDataLayout())));
12658
12659 // Input is the vector.
12660 Ops.push_back(Vec);
12661
12662 // Get widened type and narrowed type.
12663 MVT widenType;
12664 unsigned numElem = VT.getVectorNumElements();
12665
12666 EVT inputLaneType = Vec.getValueType().getVectorElementType();
12667 switch (inputLaneType.getSimpleVT().SimpleTy) {
12668 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
12669 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
12670 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
12671 default:
12672 llvm_unreachable("Invalid vector element type for padd optimization.");
12673 }
12674
12675 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
12676 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
12677 return DAG.getNode(ExtOp, dl, VT, tmp);
12678}
12679
12681 if (V->getOpcode() == ISD::UMUL_LOHI ||
12682 V->getOpcode() == ISD::SMUL_LOHI)
12683 return V;
12684 return SDValue();
12685}
12686
12687static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
12689 const ARMSubtarget *Subtarget) {
12690 if (!Subtarget->hasBaseDSP())
12691 return SDValue();
12692
12693 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
12694 // accumulates the product into a 64-bit value. The 16-bit values will
12695 // be sign extended somehow or SRA'd into 32-bit values
12696 // (addc (adde (mul 16bit, 16bit), lo), hi)
12697 SDValue Mul = AddcNode->getOperand(0);
12698 SDValue Lo = AddcNode->getOperand(1);
12699 if (Mul.getOpcode() != ISD::MUL) {
12700 Lo = AddcNode->getOperand(0);
12701 Mul = AddcNode->getOperand(1);
12702 if (Mul.getOpcode() != ISD::MUL)
12703 return SDValue();
12704 }
12705
12706 SDValue SRA = AddeNode->getOperand(0);
12707 SDValue Hi = AddeNode->getOperand(1);
12708 if (SRA.getOpcode() != ISD::SRA) {
12709 SRA = AddeNode->getOperand(1);
12710 Hi = AddeNode->getOperand(0);
12711 if (SRA.getOpcode() != ISD::SRA)
12712 return SDValue();
12713 }
12714 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
12715 if (Const->getZExtValue() != 31)
12716 return SDValue();
12717 } else
12718 return SDValue();
12719
12720 if (SRA.getOperand(0) != Mul)
12721 return SDValue();
12722
12723 SelectionDAG &DAG = DCI.DAG;
12724 SDLoc dl(AddcNode);
12725 unsigned Opcode = 0;
12726 SDValue Op0;
12727 SDValue Op1;
12728
12729 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
12730 Opcode = ARMISD::SMLALBB;
12731 Op0 = Mul.getOperand(0);
12732 Op1 = Mul.getOperand(1);
12733 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
12734 Opcode = ARMISD::SMLALBT;
12735 Op0 = Mul.getOperand(0);
12736 Op1 = Mul.getOperand(1).getOperand(0);
12737 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
12738 Opcode = ARMISD::SMLALTB;
12739 Op0 = Mul.getOperand(0).getOperand(0);
12740 Op1 = Mul.getOperand(1);
12741 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
12742 Opcode = ARMISD::SMLALTT;
12743 Op0 = Mul->getOperand(0).getOperand(0);
12744 Op1 = Mul->getOperand(1).getOperand(0);
12745 }
12746
12747 if (!Op0 || !Op1)
12748 return SDValue();
12749
12750 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
12751 Op0, Op1, Lo, Hi);
12752 // Replace the ADDs' nodes uses by the MLA node's values.
12753 SDValue HiMLALResult(SMLAL.getNode(), 1);
12754 SDValue LoMLALResult(SMLAL.getNode(), 0);
12755
12756 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
12757 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
12758 DCI.recursivelyDeleteUnusedNodes(AddeNode);
12759
12760 // Return original node to notify the driver to stop replacing.
12761 return SDValue(AddeNode, 0);
12762}
12763
12766 const ARMSubtarget *Subtarget) {
12767 // Look for multiply add opportunities.
12768 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
12769 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
12770 // a glue link from the first add to the second add.
12771 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
12772 // a S/UMLAL instruction.
12773 // UMUL_LOHI
12774 // / :lo \ :hi
12775 // V \ [no multiline comment]
12776 // loAdd -> ADDC |
12777 // \ :carry /
12778 // V V
12779 // ADDE <- hiAdd
12780 //
12781 // In the special case where only the higher part of a signed result is used
12782 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
12783 // a constant with the exact value of 0x80000000, we recognize we are dealing
12784 // with a "rounded multiply and add" (or subtract) and transform it into
12785 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
12786
12787 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
12788 AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
12789 "Expect an ADDE or SUBE");
12790
12791 assert(AddeSubeNode->getNumOperands() == 3 &&
12792 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
12793 "ADDE node has the wrong inputs");
12794
12795 if (AddeSubeNode->hasAnyUseOfValue(1))
12796 return SDValue();
12797
12798 // Check that we are chained to the right ADDC or SUBC node.
12799 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
12800 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
12801 AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
12802 (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
12803 AddcSubcNode->getOpcode() != ARMISD::SUBC))
12804 return SDValue();
12805
12806 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
12807 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
12808
12809 // Check if the two operands are from the same mul_lohi node.
12810 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
12811 return SDValue();
12812
12813 assert(AddcSubcNode->getNumValues() == 2 &&
12814 AddcSubcNode->getValueType(0) == MVT::i32 &&
12815 "Expect ADDC with two result values. First: i32");
12816
12817 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
12818 // maybe a SMLAL which multiplies two 16-bit values.
12819 if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
12820 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
12821 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
12822 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
12823 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
12824 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
12825
12826 // Check for the triangle shape.
12827 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
12828 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
12829
12830 // Make sure that the ADDE/SUBE operands are not coming from the same node.
12831 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
12832 return SDValue();
12833
12834 // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
12835 bool IsLeftOperandMUL = false;
12836 SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
12837 if (MULOp == SDValue())
12838 MULOp = findMUL_LOHI(AddeSubeOp1);
12839 else
12840 IsLeftOperandMUL = true;
12841 if (MULOp == SDValue())
12842 return SDValue();
12843
12844 // Figure out the right opcode.
12845 unsigned Opc = MULOp->getOpcode();
12846 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
12847
12848 // Figure out the high and low input values to the MLAL node.
12849 SDValue *HiAddSub = nullptr;
12850 SDValue *LoMul = nullptr;
12851 SDValue *LowAddSub = nullptr;
12852
12853 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
12854 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
12855 return SDValue();
12856
12857 if (IsLeftOperandMUL)
12858 HiAddSub = &AddeSubeOp1;
12859 else
12860 HiAddSub = &AddeSubeOp0;
12861
12862 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
12863 // whose low result is fed to the ADDC/SUBC we are checking.
12864
12865 if (AddcSubcOp0 == MULOp.getValue(0)) {
12866 LoMul = &AddcSubcOp0;
12867 LowAddSub = &AddcSubcOp1;
12868 }
12869 if (AddcSubcOp1 == MULOp.getValue(0)) {
12870 LoMul = &AddcSubcOp1;
12871 LowAddSub = &AddcSubcOp0;
12872 }
12873
12874 if (!LoMul)
12875 return SDValue();
12876
12877 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
12878 // the replacement below will create a cycle.
12879 if (AddcSubcNode == HiAddSub->getNode() ||
12880 AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
12881 return SDValue();
12882
12883 // Create the merged node.
12884 SelectionDAG &DAG = DCI.DAG;
12885
12886 // Start building operand list.
12888 Ops.push_back(LoMul->getOperand(0));
12889 Ops.push_back(LoMul->getOperand(1));
12890
12891 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be
12892 // the case, we must be doing signed multiplication and only use the higher
12893 // part of the result of the MLAL, furthermore the LowAddSub must be a constant
12894 // addition or subtraction with the value of 0x800000.
12895 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
12896 FinalOpc == ARMISD::SMLAL &&
12897 LowAddSub->getNode()->getOpcode() == ISD::Constant &&
12898 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
12899 0x80000000) {
12900 Ops.push_back(*HiAddSub);
12901 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
12902 FinalOpc = ARMISD::SMMLSR;
12903 } else {
12904 FinalOpc = ARMISD::SMMLAR;
12905 }
12906 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
12907 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
12908
12909 return SDValue(AddeSubeNode, 0);
12910 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
12911 // SMMLS is generated during instruction selection and the rest of this
12912 // function can not handle the case where AddcSubcNode is a SUBC.
12913 return SDValue();
12914
12915 // Finish building the operand list for {U/S}MLAL
12916 Ops.push_back(*LowAddSub);
12917 Ops.push_back(*HiAddSub);
12918
12919 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
12920 DAG.getVTList(MVT::i32, MVT::i32), Ops);
12921
12922 // Replace the ADDs' nodes uses by the MLA node's values.
12923 SDValue HiMLALResult(MLALNode.getNode(), 1);
12924 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
12925
12926 SDValue LoMLALResult(MLALNode.getNode(), 0);
12927 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
12928
12929 // Return original node to notify the driver to stop replacing.
12930 return SDValue(AddeSubeNode, 0);
12931}
12932
12935 const ARMSubtarget *Subtarget) {
12936 // UMAAL is similar to UMLAL except that it adds two unsigned values.
12937 // While trying to combine for the other MLAL nodes, first search for the
12938 // chance to use UMAAL. Check if Addc uses a node which has already
12939 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
12940 // as the addend, and it's handled in PerformUMLALCombine.
12941
12942 if (AddeNode->hasAnyUseOfValue(1))
12943 return SDValue();
12944
12945 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
12946 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
12947
12948 // Check that we have a glued ADDC node.
12949 SDNode* AddcNode = AddeNode->getOperand(2).getNode();
12950 if (AddcNode->getOpcode() != ARMISD::ADDC)
12951 return SDValue();
12952
12953 // Find the converted UMAAL or quit if it doesn't exist.
12954 SDNode *UmlalNode = nullptr;
12955 SDValue AddHi;
12956 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
12957 UmlalNode = AddcNode->getOperand(0).getNode();
12958 AddHi = AddcNode->getOperand(1);
12959 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
12960 UmlalNode = AddcNode->getOperand(1).getNode();
12961 AddHi = AddcNode->getOperand(0);
12962 } else {
12963 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
12964 }
12965
12966 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
12967 // the ADDC as well as Zero.
12968 if (!isNullConstant(UmlalNode->getOperand(3)))
12969 return SDValue();
12970
12971 if ((isNullConstant(AddeNode->getOperand(0)) &&
12972 AddeNode->getOperand(1).getNode() == UmlalNode) ||
12973 (AddeNode->getOperand(0).getNode() == UmlalNode &&
12974 isNullConstant(AddeNode->getOperand(1)))) {
12975 SelectionDAG &DAG = DCI.DAG;
12976 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
12977 UmlalNode->getOperand(2), AddHi };
12978 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
12979 DAG.getVTList(MVT::i32, MVT::i32), Ops);
12980
12981 // Replace the ADDs' nodes uses by the UMAAL node's values.
12982 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
12983 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
12984
12985 // Return original node to notify the driver to stop replacing.
12986 return SDValue(AddeNode, 0);
12987 }
12988 return SDValue();
12989}
12990
12992 const ARMSubtarget *Subtarget) {
12993 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
12994 return SDValue();
12995
12996 // Check that we have a pair of ADDC and ADDE as operands.
12997 // Both addends of the ADDE must be zero.
12998 SDNode* AddcNode = N->getOperand(2).getNode();
12999 SDNode* AddeNode = N->getOperand(3).getNode();
13000 if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
13001 (AddeNode->getOpcode() == ARMISD::ADDE) &&
13002 isNullConstant(AddeNode->getOperand(0)) &&
13003 isNullConstant(AddeNode->getOperand(1)) &&
13004 (AddeNode->getOperand(2).getNode() == AddcNode))
13005 return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
13006 DAG.getVTList(MVT::i32, MVT::i32),
13007 {N->getOperand(0), N->getOperand(1),
13008 AddcNode->getOperand(0), AddcNode->getOperand(1)});
13009 else
13010 return SDValue();
13011}
13012
13015 const ARMSubtarget *Subtarget) {
13016 SelectionDAG &DAG(DCI.DAG);
13017
13018 if (N->getOpcode() == ARMISD::SUBC && N->hasAnyUseOfValue(1)) {
13019 // (SUBC (ADDE 0, 0, C), 1) -> C
13020 SDValue LHS = N->getOperand(0);
13021 SDValue RHS = N->getOperand(1);
13022 if (LHS->getOpcode() == ARMISD::ADDE &&
13023 isNullConstant(LHS->getOperand(0)) &&
13024 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
13025 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
13026 }
13027 }
13028
13029 if (Subtarget->isThumb1Only()) {
13030 SDValue RHS = N->getOperand(1);
13032 int32_t imm = C->getSExtValue();
13033 if (imm < 0 && imm > std::numeric_limits<int>::min()) {
13034 SDLoc DL(N);
13035 RHS = DAG.getConstant(-imm, DL, MVT::i32);
13036 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
13037 : ARMISD::ADDC;
13038 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
13039 }
13040 }
13041 }
13042
13043 return SDValue();
13044}
13045
13048 const ARMSubtarget *Subtarget) {
13049 if (Subtarget->isThumb1Only()) {
13050 SelectionDAG &DAG = DCI.DAG;
13051 SDValue RHS = N->getOperand(1);
13053 int64_t imm = C->getSExtValue();
13054 if (imm < 0) {
13055 SDLoc DL(N);
13056
13057 // The with-carry-in form matches bitwise not instead of the negation.
13058 // Effectively, the inverse interpretation of the carry flag already
13059 // accounts for part of the negation.
13060 RHS = DAG.getConstant(~imm, DL, MVT::i32);
13061
13062 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
13063 : ARMISD::ADDE;
13064 return DAG.getNode(Opcode, DL, N->getVTList(),
13065 N->getOperand(0), RHS, N->getOperand(2));
13066 }
13067 }
13068 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
13069 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
13070 }
13071 return SDValue();
13072}
13073
13076 const ARMSubtarget *Subtarget) {
13077 if (!Subtarget->hasMVEIntegerOps())
13078 return SDValue();
13079
13080 SDLoc dl(N);
13081 SDValue SetCC;
13082 SDValue LHS;
13083 SDValue RHS;
13085 SDValue TrueVal;
13086 SDValue FalseVal;
13087
13088 if (N->getOpcode() == ISD::SELECT &&
13089 N->getOperand(0)->getOpcode() == ISD::SETCC) {
13090 SetCC = N->getOperand(0);
13091 LHS = SetCC->getOperand(0);
13092 RHS = SetCC->getOperand(1);
13093 CC = SetCC->getOperandCondCode(2);
13094 TrueVal = N->getOperand(1);
13095 FalseVal = N->getOperand(2);
13096 } else if (N->getOpcode() == ISD::SELECT_CC) {
13097 LHS = N->getOperand(0);
13098 RHS = N->getOperand(1);
13099 CC = N->getOperandCondCode(4);
13100 TrueVal = N->getOperand(2);
13101 FalseVal = N->getOperand(3);
13102 } else {
13103 return SDValue();
13104 }
13105
13106 unsigned int Opcode = 0;
13107 if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMIN ||
13108 FalseVal->getOpcode() == ISD::VECREDUCE_UMIN) &&
13109 (CC == ISD::SETULT || CC == ISD::SETUGT)) {
13110 Opcode = ARMISD::VMINVu;
13111 if (CC == ISD::SETUGT)
13112 std::swap(TrueVal, FalseVal);
13113 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMIN ||
13114 FalseVal->getOpcode() == ISD::VECREDUCE_SMIN) &&
13115 (CC == ISD::SETLT || CC == ISD::SETGT)) {
13116 Opcode = ARMISD::VMINVs;
13117 if (CC == ISD::SETGT)
13118 std::swap(TrueVal, FalseVal);
13119 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMAX ||
13120 FalseVal->getOpcode() == ISD::VECREDUCE_UMAX) &&
13121 (CC == ISD::SETUGT || CC == ISD::SETULT)) {
13122 Opcode = ARMISD::VMAXVu;
13123 if (CC == ISD::SETULT)
13124 std::swap(TrueVal, FalseVal);
13125 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMAX ||
13126 FalseVal->getOpcode() == ISD::VECREDUCE_SMAX) &&
13127 (CC == ISD::SETGT || CC == ISD::SETLT)) {
13128 Opcode = ARMISD::VMAXVs;
13129 if (CC == ISD::SETLT)
13130 std::swap(TrueVal, FalseVal);
13131 } else
13132 return SDValue();
13133
13134 // Normalise to the right hand side being the vector reduction
13135 switch (TrueVal->getOpcode()) {
13140 std::swap(LHS, RHS);
13141 std::swap(TrueVal, FalseVal);
13142 break;
13143 }
13144
13145 EVT VectorType = FalseVal->getOperand(0).getValueType();
13146
13147 if (VectorType != MVT::v16i8 && VectorType != MVT::v8i16 &&
13148 VectorType != MVT::v4i32)
13149 return SDValue();
13150
13151 EVT VectorScalarType = VectorType.getVectorElementType();
13152
13153 // The values being selected must also be the ones being compared
13154 if (TrueVal != LHS || FalseVal != RHS)
13155 return SDValue();
13156
13157 EVT LeftType = LHS->getValueType(0);
13158 EVT RightType = RHS->getValueType(0);
13159
13160 // The types must match the reduced type too
13161 if (LeftType != VectorScalarType || RightType != VectorScalarType)
13162 return SDValue();
13163
13164 // Legalise the scalar to an i32
13165 if (VectorScalarType != MVT::i32)
13166 LHS = DCI.DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13167
13168 // Generate the reduction as an i32 for legalisation purposes
13169 auto Reduction =
13170 DCI.DAG.getNode(Opcode, dl, MVT::i32, LHS, RHS->getOperand(0));
13171
13172 // The result isn't actually an i32 so truncate it back to its original type
13173 if (VectorScalarType != MVT::i32)
13174 Reduction = DCI.DAG.getNode(ISD::TRUNCATE, dl, VectorScalarType, Reduction);
13175
13176 return Reduction;
13177}
13178
13179// A special combine for the vqdmulh family of instructions. This is one of the
13180// potential set of patterns that could patch this instruction. The base pattern
13181// you would expect to be min(max(ashr(mul(mul(sext(x), 2), sext(y)), 16))).
13182// This matches the different min(max(ashr(mul(mul(sext(x), sext(y)), 2), 16))),
13183// which llvm will have optimized to min(ashr(mul(sext(x), sext(y)), 15))) as
13184// the max is unnecessary.
13186 EVT VT = N->getValueType(0);
13187 SDValue Shft;
13188 ConstantSDNode *Clamp;
13189
13190 if (!VT.isVector() || VT.getScalarSizeInBits() > 64)
13191 return SDValue();
13192
13193 if (N->getOpcode() == ISD::SMIN) {
13194 Shft = N->getOperand(0);
13195 Clamp = isConstOrConstSplat(N->getOperand(1));
13196 } else if (N->getOpcode() == ISD::VSELECT) {
13197 // Detect a SMIN, which for an i64 node will be a vselect/setcc, not a smin.
13198 SDValue Cmp = N->getOperand(0);
13199 if (Cmp.getOpcode() != ISD::SETCC ||
13200 Cmp.getOperandCondCode(2) != ISD::SETLT ||
13201 Cmp.getOperand(0) != N->getOperand(1) ||
13202 Cmp.getOperand(1) != N->getOperand(2))
13203 return SDValue();
13204 Shft = N->getOperand(1);
13205 Clamp = isConstOrConstSplat(N->getOperand(2));
13206 } else
13207 return SDValue();
13208
13209 if (!Clamp)
13210 return SDValue();
13211
13212 MVT ScalarType;
13213 int ShftAmt = 0;
13214 switch (Clamp->getSExtValue()) {
13215 case (1 << 7) - 1:
13216 ScalarType = MVT::i8;
13217 ShftAmt = 7;
13218 break;
13219 case (1 << 15) - 1:
13220 ScalarType = MVT::i16;
13221 ShftAmt = 15;
13222 break;
13223 case (1ULL << 31) - 1:
13224 ScalarType = MVT::i32;
13225 ShftAmt = 31;
13226 break;
13227 default:
13228 return SDValue();
13229 }
13230
13231 if (Shft.getOpcode() != ISD::SRA)
13232 return SDValue();
13234 if (!N1 || N1->getSExtValue() != ShftAmt)
13235 return SDValue();
13236
13237 SDValue Mul = Shft.getOperand(0);
13238 if (Mul.getOpcode() != ISD::MUL)
13239 return SDValue();
13240
13241 SDValue Ext0 = Mul.getOperand(0);
13242 SDValue Ext1 = Mul.getOperand(1);
13243 if (Ext0.getOpcode() != ISD::SIGN_EXTEND ||
13244 Ext1.getOpcode() != ISD::SIGN_EXTEND)
13245 return SDValue();
13246 EVT VecVT = Ext0.getOperand(0).getValueType();
13247 if (!VecVT.isPow2VectorType() || VecVT.getVectorNumElements() == 1)
13248 return SDValue();
13249 if (Ext1.getOperand(0).getValueType() != VecVT ||
13250 VecVT.getScalarType() != ScalarType ||
13251 VT.getScalarSizeInBits() < ScalarType.getScalarSizeInBits() * 2)
13252 return SDValue();
13253
13254 SDLoc DL(Mul);
13255 unsigned LegalLanes = 128 / (ShftAmt + 1);
13256 EVT LegalVecVT = MVT::getVectorVT(ScalarType, LegalLanes);
13257 // For types smaller than legal vectors extend to be legal and only use needed
13258 // lanes.
13259 if (VecVT.getSizeInBits() < 128) {
13260 EVT ExtVecVT =
13262 VecVT.getVectorNumElements());
13263 SDValue Inp0 =
13264 DAG.getNode(ISD::ANY_EXTEND, DL, ExtVecVT, Ext0.getOperand(0));
13265 SDValue Inp1 =
13266 DAG.getNode(ISD::ANY_EXTEND, DL, ExtVecVT, Ext1.getOperand(0));
13267 Inp0 = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, LegalVecVT, Inp0);
13268 Inp1 = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, LegalVecVT, Inp1);
13269 SDValue VQDMULH = DAG.getNode(ARMISD::VQDMULH, DL, LegalVecVT, Inp0, Inp1);
13270 SDValue Trunc = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, ExtVecVT, VQDMULH);
13271 Trunc = DAG.getNode(ISD::TRUNCATE, DL, VecVT, Trunc);
13272 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Trunc);
13273 }
13274
13275 // For larger types, split into legal sized chunks.
13276 assert(VecVT.getSizeInBits() % 128 == 0 && "Expected a power2 type");
13277 unsigned NumParts = VecVT.getSizeInBits() / 128;
13279 for (unsigned I = 0; I < NumParts; ++I) {
13280 SDValue Inp0 =
13281 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, LegalVecVT, Ext0.getOperand(0),
13282 DAG.getVectorIdxConstant(I * LegalLanes, DL));
13283 SDValue Inp1 =
13284 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, LegalVecVT, Ext1.getOperand(0),
13285 DAG.getVectorIdxConstant(I * LegalLanes, DL));
13286 SDValue VQDMULH = DAG.getNode(ARMISD::VQDMULH, DL, LegalVecVT, Inp0, Inp1);
13287 Parts.push_back(VQDMULH);
13288 }
13289 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT,
13290 DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Parts));
13291}
13292
13295 const ARMSubtarget *Subtarget) {
13296 if (!Subtarget->hasMVEIntegerOps())
13297 return SDValue();
13298
13299 // Constant fold vselect 0, A, B -> B
13300 // and vselect 0xffff, A, B -> A
13301 if (N->getOperand(0).getOpcode() == ARMISD::PREDICATE_CAST &&
13302 isa<ConstantSDNode>(N->getOperand(0).getOperand(0))) {
13303 unsigned C = N->getOperand(0).getConstantOperandVal(0);
13304 if (C == 0)
13305 return N->getOperand(2);
13306 if (C == 0xffff)
13307 return N->getOperand(1);
13308 }
13309
13310 if (SDValue V = PerformVQDMULHCombine(N, DCI.DAG))
13311 return V;
13312
13313 // Transforms vselect(not(cond), lhs, rhs) into vselect(cond, rhs, lhs).
13314 //
13315 // We need to re-implement this optimization here as the implementation in the
13316 // Target-Independent DAGCombiner does not handle the kind of constant we make
13317 // (it calls isConstOrConstSplat with AllowTruncation set to false - and for
13318 // good reason, allowing truncation there would break other targets).
13319 //
13320 // Currently, this is only done for MVE, as it's the only target that benefits
13321 // from this transformation (e.g. VPNOT+VPSEL becomes a single VPSEL).
13322 if (N->getOperand(0).getOpcode() != ISD::XOR)
13323 return SDValue();
13324 SDValue XOR = N->getOperand(0);
13325
13326 // Check if the XOR's RHS is either a 1, or a BUILD_VECTOR of 1s.
13327 // It is important to check with truncation allowed as the BUILD_VECTORs we
13328 // generate in those situations will truncate their operands.
13329 ConstantSDNode *Const =
13330 isConstOrConstSplat(XOR->getOperand(1), /*AllowUndefs*/ false,
13331 /*AllowTruncation*/ true);
13332 if (!Const || !Const->isOne())
13333 return SDValue();
13334
13335 // Rewrite into vselect(cond, rhs, lhs).
13336 SDValue Cond = XOR->getOperand(0);
13337 SDValue LHS = N->getOperand(1);
13338 SDValue RHS = N->getOperand(2);
13339 EVT Type = N->getValueType(0);
13340 return DCI.DAG.getNode(ISD::VSELECT, SDLoc(N), Type, Cond, RHS, LHS);
13341}
13342
13343// Convert vsetcc([0,1,2,..], splat(n), ult) -> vctp n
13346 const ARMSubtarget *Subtarget) {
13347 SDValue Op0 = N->getOperand(0);
13348 SDValue Op1 = N->getOperand(1);
13349 ISD::CondCode CC = N->getOperandCondCode(2);
13350 EVT VT = N->getValueType(0);
13351
13352 if (!Subtarget->hasMVEIntegerOps() ||
13354 return SDValue();
13355
13356 if (CC == ISD::SETUGT) {
13357 std::swap(Op0, Op1);
13358 CC = ISD::SETULT;
13359 }
13360
13361 if (CC != ISD::SETULT || VT.getScalarSizeInBits() != 1 ||
13363 return SDValue();
13364
13365 // Check first operand is BuildVector of 0,1,2,...
13366 for (unsigned I = 0; I < VT.getVectorNumElements(); I++) {
13367 if (!Op0.getOperand(I).isUndef() &&
13369 Op0.getConstantOperandVal(I) == I))
13370 return SDValue();
13371 }
13372
13373 // The second is a Splat of Op1S
13374 SDValue Op1S = DCI.DAG.getSplatValue(Op1);
13375 if (!Op1S)
13376 return SDValue();
13377
13378 unsigned Opc;
13379 switch (VT.getVectorNumElements()) {
13380 case 4:
13381 Opc = Intrinsic::arm_mve_vctp32;
13382 break;
13383 case 8:
13384 Opc = Intrinsic::arm_mve_vctp16;
13385 break;
13386 case 16:
13387 Opc = Intrinsic::arm_mve_vctp8;
13388 break;
13389 default:
13390 return SDValue();
13391 }
13392
13393 SDLoc DL(N);
13394 return DCI.DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13395 DCI.DAG.getConstant(Opc, DL, MVT::i32),
13396 DCI.DAG.getZExtOrTrunc(Op1S, DL, MVT::i32));
13397}
13398
13399/// PerformADDECombine - Target-specific dag combine transform from
13400/// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
13401/// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
13404 const ARMSubtarget *Subtarget) {
13405 // Only ARM and Thumb2 support UMLAL/SMLAL.
13406 if (Subtarget->isThumb1Only())
13407 return PerformAddeSubeCombine(N, DCI, Subtarget);
13408
13409 // Only perform the checks after legalize when the pattern is available.
13410 if (DCI.isBeforeLegalize()) return SDValue();
13411
13412 return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
13413}
13414
13415/// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
13416/// operands N0 and N1. This is a helper for PerformADDCombine that is
13417/// called with the default operands, and if that fails, with commuted
13418/// operands.
13421 const ARMSubtarget *Subtarget){
13422 // Attempt to create vpadd for this add.
13423 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
13424 return Result;
13425
13426 // Attempt to create vpaddl for this add.
13427 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
13428 return Result;
13429 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
13430 Subtarget))
13431 return Result;
13432
13433 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
13434 if (N0.getNode()->hasOneUse())
13435 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
13436 return Result;
13437 return SDValue();
13438}
13439
13441 EVT VT = N->getValueType(0);
13442 SDValue N0 = N->getOperand(0);
13443 SDValue N1 = N->getOperand(1);
13444 SDLoc dl(N);
13445
13446 auto IsVecReduce = [](SDValue Op) {
13447 switch (Op.getOpcode()) {
13448 case ISD::VECREDUCE_ADD:
13449 case ARMISD::VADDVs:
13450 case ARMISD::VADDVu:
13451 case ARMISD::VMLAVs:
13452 case ARMISD::VMLAVu:
13453 return true;
13454 }
13455 return false;
13456 };
13457
13458 auto DistrubuteAddAddVecReduce = [&](SDValue N0, SDValue N1) {
13459 // Distribute add(X, add(vecreduce(Y), vecreduce(Z))) ->
13460 // add(add(X, vecreduce(Y)), vecreduce(Z))
13461 // to make better use of vaddva style instructions.
13462 if (VT == MVT::i32 && N1.getOpcode() == ISD::ADD && !IsVecReduce(N0) &&
13463 IsVecReduce(N1.getOperand(0)) && IsVecReduce(N1.getOperand(1)) &&
13464 !isa<ConstantSDNode>(N0) && N1->hasOneUse()) {
13465 SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, N0, N1.getOperand(0));
13466 return DAG.getNode(ISD::ADD, dl, VT, Add0, N1.getOperand(1));
13467 }
13468 // And turn add(add(A, reduce(B)), add(C, reduce(D))) ->
13469 // add(add(add(A, C), reduce(B)), reduce(D))
13470 if (VT == MVT::i32 && N0.getOpcode() == ISD::ADD &&
13471 N1.getOpcode() == ISD::ADD && N0->hasOneUse() && N1->hasOneUse()) {
13472 unsigned N0RedOp = 0;
13473 if (!IsVecReduce(N0.getOperand(N0RedOp))) {
13474 N0RedOp = 1;
13475 if (!IsVecReduce(N0.getOperand(N0RedOp)))
13476 return SDValue();
13477 }
13478
13479 unsigned N1RedOp = 0;
13480 if (!IsVecReduce(N1.getOperand(N1RedOp)))
13481 N1RedOp = 1;
13482 if (!IsVecReduce(N1.getOperand(N1RedOp)))
13483 return SDValue();
13484
13485 SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, N0.getOperand(1 - N0RedOp),
13486 N1.getOperand(1 - N1RedOp));
13487 SDValue Add1 =
13488 DAG.getNode(ISD::ADD, dl, VT, Add0, N0.getOperand(N0RedOp));
13489 return DAG.getNode(ISD::ADD, dl, VT, Add1, N1.getOperand(N1RedOp));
13490 }
13491 return SDValue();
13492 };
13493 if (SDValue R = DistrubuteAddAddVecReduce(N0, N1))
13494 return R;
13495 if (SDValue R = DistrubuteAddAddVecReduce(N1, N0))
13496 return R;
13497
13498 // Distribute add(vecreduce(load(Y)), vecreduce(load(Z)))
13499 // Or add(add(X, vecreduce(load(Y))), vecreduce(load(Z)))
13500 // by ascending load offsets. This can help cores prefetch if the order of
13501 // loads is more predictable.
13502 auto DistrubuteVecReduceLoad = [&](SDValue N0, SDValue N1, bool IsForward) {
13503 // Check if two reductions are known to load data where one is before/after
13504 // another. Return negative if N0 loads data before N1, positive if N1 is
13505 // before N0 and 0 otherwise if nothing is known.
13506 auto IsKnownOrderedLoad = [&](SDValue N0, SDValue N1) {
13507 // Look through to the first operand of a MUL, for the VMLA case.
13508 // Currently only looks at the first operand, in the hope they are equal.
13509 if (N0.getOpcode() == ISD::MUL)
13510 N0 = N0.getOperand(0);
13511 if (N1.getOpcode() == ISD::MUL)
13512 N1 = N1.getOperand(0);
13513
13514 // Return true if the two operands are loads to the same object and the
13515 // offset of the first is known to be less than the offset of the second.
13516 LoadSDNode *Load0 = dyn_cast<LoadSDNode>(N0);
13517 LoadSDNode *Load1 = dyn_cast<LoadSDNode>(N1);
13518 if (!Load0 || !Load1 || Load0->getChain() != Load1->getChain() ||
13519 !Load0->isSimple() || !Load1->isSimple() || Load0->isIndexed() ||
13520 Load1->isIndexed())
13521 return 0;
13522
13523 auto BaseLocDecomp0 = BaseIndexOffset::match(Load0, DAG);
13524 auto BaseLocDecomp1 = BaseIndexOffset::match(Load1, DAG);
13525
13526 if (!BaseLocDecomp0.getBase() ||
13527 BaseLocDecomp0.getBase() != BaseLocDecomp1.getBase() ||
13528 !BaseLocDecomp0.hasValidOffset() || !BaseLocDecomp1.hasValidOffset())
13529 return 0;
13530 if (BaseLocDecomp0.getOffset() < BaseLocDecomp1.getOffset())
13531 return -1;
13532 if (BaseLocDecomp0.getOffset() > BaseLocDecomp1.getOffset())
13533 return 1;
13534 return 0;
13535 };
13536
13537 SDValue X;
13538 if (N0.getOpcode() == ISD::ADD && N0->hasOneUse()) {
13539 if (IsVecReduce(N0.getOperand(0)) && IsVecReduce(N0.getOperand(1))) {
13540 int IsBefore = IsKnownOrderedLoad(N0.getOperand(0).getOperand(0),
13541 N0.getOperand(1).getOperand(0));
13542 if (IsBefore < 0) {
13543 X = N0.getOperand(0);
13544 N0 = N0.getOperand(1);
13545 } else if (IsBefore > 0) {
13546 X = N0.getOperand(1);
13547 N0 = N0.getOperand(0);
13548 } else
13549 return SDValue();
13550 } else if (IsVecReduce(N0.getOperand(0))) {
13551 X = N0.getOperand(1);
13552 N0 = N0.getOperand(0);
13553 } else if (IsVecReduce(N0.getOperand(1))) {
13554 X = N0.getOperand(0);
13555 N0 = N0.getOperand(1);
13556 } else
13557 return SDValue();
13558 } else if (IsForward && IsVecReduce(N0) && IsVecReduce(N1) &&
13559 IsKnownOrderedLoad(N0.getOperand(0), N1.getOperand(0)) < 0) {
13560 // Note this is backward to how you would expect. We create
13561 // add(reduce(load + 16), reduce(load + 0)) so that the
13562 // add(reduce(load+16), X) is combined into VADDVA(X, load+16)), leaving
13563 // the X as VADDV(load + 0)
13564 return DAG.getNode(ISD::ADD, dl, VT, N1, N0);
13565 } else
13566 return SDValue();
13567
13568 if (!IsVecReduce(N0) || !IsVecReduce(N1))
13569 return SDValue();
13570
13571 if (IsKnownOrderedLoad(N1.getOperand(0), N0.getOperand(0)) >= 0)
13572 return SDValue();
13573
13574 // Switch from add(add(X, N0), N1) to add(add(X, N1), N0)
13575 SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, X, N1);
13576 return DAG.getNode(ISD::ADD, dl, VT, Add0, N0);
13577 };
13578 if (SDValue R = DistrubuteVecReduceLoad(N0, N1, true))
13579 return R;
13580 if (SDValue R = DistrubuteVecReduceLoad(N1, N0, false))
13581 return R;
13582 return SDValue();
13583}
13584
13586 const ARMSubtarget *Subtarget) {
13587 if (!Subtarget->hasMVEIntegerOps())
13588 return SDValue();
13589
13591 return R;
13592
13593 EVT VT = N->getValueType(0);
13594 SDValue N0 = N->getOperand(0);
13595 SDValue N1 = N->getOperand(1);
13596 SDLoc dl(N);
13597
13598 if (VT != MVT::i64)
13599 return SDValue();
13600
13601 // We are looking for a i64 add of a VADDLVx. Due to these being i64's, this
13602 // will look like:
13603 // t1: i32,i32 = ARMISD::VADDLVs x
13604 // t2: i64 = build_pair t1, t1:1
13605 // t3: i64 = add t2, y
13606 // Otherwise we try to push the add up above VADDLVAx, to potentially allow
13607 // the add to be simplified separately.
13608 // We also need to check for sext / zext and commutitive adds.
13609 auto MakeVecReduce = [&](unsigned Opcode, unsigned OpcodeA, SDValue NA,
13610 SDValue NB) {
13611 if (NB->getOpcode() != ISD::BUILD_PAIR)
13612 return SDValue();
13613 SDValue VecRed = NB->getOperand(0);
13614 if ((VecRed->getOpcode() != Opcode && VecRed->getOpcode() != OpcodeA) ||
13615 VecRed.getResNo() != 0 ||
13616 NB->getOperand(1) != SDValue(VecRed.getNode(), 1))
13617 return SDValue();
13618
13619 if (VecRed->getOpcode() == OpcodeA) {
13620 // add(NA, VADDLVA(Inp), Y) -> VADDLVA(add(NA, Inp), Y)
13621 SDValue Inp = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64,
13622 VecRed.getOperand(0), VecRed.getOperand(1));
13623 NA = DAG.getNode(ISD::ADD, dl, MVT::i64, Inp, NA);
13624 }
13625
13627 std::tie(Ops[0], Ops[1]) = DAG.SplitScalar(NA, dl, MVT::i32, MVT::i32);
13628
13629 unsigned S = VecRed->getOpcode() == OpcodeA ? 2 : 0;
13630 for (unsigned I = S, E = VecRed.getNumOperands(); I < E; I++)
13631 Ops.push_back(VecRed->getOperand(I));
13632 SDValue Red =
13633 DAG.getNode(OpcodeA, dl, DAG.getVTList({MVT::i32, MVT::i32}), Ops);
13634 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Red,
13635 SDValue(Red.getNode(), 1));
13636 };
13637
13638 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N0, N1))
13639 return M;
13640 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N0, N1))
13641 return M;
13642 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N1, N0))
13643 return M;
13644 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N1, N0))
13645 return M;
13646 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N0, N1))
13647 return M;
13648 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N0, N1))
13649 return M;
13650 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N1, N0))
13651 return M;
13652 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N1, N0))
13653 return M;
13654 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N0, N1))
13655 return M;
13656 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N0, N1))
13657 return M;
13658 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N1, N0))
13659 return M;
13660 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N1, N0))
13661 return M;
13662 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N0, N1))
13663 return M;
13664 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N0, N1))
13665 return M;
13666 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N1, N0))
13667 return M;
13668 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N1, N0))
13669 return M;
13670 return SDValue();
13671}
13672
13673bool
13675 CombineLevel Level) const {
13676 assert((N->getOpcode() == ISD::SHL || N->getOpcode() == ISD::SRA ||
13677 N->getOpcode() == ISD::SRL) &&
13678 "Expected shift op");
13679
13680 SDValue ShiftLHS = N->getOperand(0);
13681 if (!ShiftLHS->hasOneUse())
13682 return false;
13683
13684 if (ShiftLHS.getOpcode() == ISD::SIGN_EXTEND &&
13685 !ShiftLHS.getOperand(0)->hasOneUse())
13686 return false;
13687
13688 if (Level == BeforeLegalizeTypes)
13689 return true;
13690
13691 if (N->getOpcode() != ISD::SHL)
13692 return true;
13693
13694 if (Subtarget->isThumb1Only()) {
13695 // Avoid making expensive immediates by commuting shifts. (This logic
13696 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
13697 // for free.)
13698 if (N->getOpcode() != ISD::SHL)
13699 return true;
13700 SDValue N1 = N->getOperand(0);
13701 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
13702 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
13703 return true;
13704 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
13705 if (Const->getAPIntValue().ult(256))
13706 return false;
13707 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
13708 Const->getAPIntValue().sgt(-256))
13709 return false;
13710 }
13711 return true;
13712 }
13713
13714 // Turn off commute-with-shift transform after legalization, so it doesn't
13715 // conflict with PerformSHLSimplify. (We could try to detect when
13716 // PerformSHLSimplify would trigger more precisely, but it isn't
13717 // really necessary.)
13718 return false;
13719}
13720
13722 const SDNode *N) const {
13723 assert(N->getOpcode() == ISD::XOR &&
13724 (N->getOperand(0).getOpcode() == ISD::SHL ||
13725 N->getOperand(0).getOpcode() == ISD::SRL) &&
13726 "Expected XOR(SHIFT) pattern");
13727
13728 // Only commute if the entire NOT mask is a hidden shifted mask.
13729 auto *XorC = dyn_cast<ConstantSDNode>(N->getOperand(1));
13730 auto *ShiftC = dyn_cast<ConstantSDNode>(N->getOperand(0).getOperand(1));
13731 if (XorC && ShiftC) {
13732 unsigned MaskIdx, MaskLen;
13733 if (XorC->getAPIntValue().isShiftedMask(MaskIdx, MaskLen)) {
13734 unsigned ShiftAmt = ShiftC->getZExtValue();
13735 unsigned BitWidth = N->getValueType(0).getScalarSizeInBits();
13736 if (N->getOperand(0).getOpcode() == ISD::SHL)
13737 return MaskIdx == ShiftAmt && MaskLen == (BitWidth - ShiftAmt);
13738 return MaskIdx == 0 && MaskLen == (BitWidth - ShiftAmt);
13739 }
13740 }
13741
13742 return false;
13743}
13744
13746 const SDNode *N) const {
13747 assert(((N->getOpcode() == ISD::SHL &&
13748 N->getOperand(0).getOpcode() == ISD::SRL) ||
13749 (N->getOpcode() == ISD::SRL &&
13750 N->getOperand(0).getOpcode() == ISD::SHL)) &&
13751 "Expected shift-shift mask");
13752
13753 if (!Subtarget->isThumb1Only())
13754 return true;
13755
13756 EVT VT = N->getValueType(0);
13757 if (VT.getScalarSizeInBits() > 32)
13758 return true;
13759
13760 return false;
13761}
13762
13764 unsigned BinOpcode, EVT VT, unsigned SelectOpcode, SDValue X,
13765 SDValue Y) const {
13766 return Subtarget->hasMVEIntegerOps() && isTypeLegal(VT) &&
13767 SelectOpcode == ISD::VSELECT;
13768}
13769
13771 if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps()) {
13772 if (Subtarget->isThumb1Only())
13773 return VT.getScalarSizeInBits() <= 32;
13774 return true;
13775 }
13776 return VT.isScalarInteger();
13777}
13778
13780 EVT VT) const {
13781 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
13782 return false;
13783
13784 switch (FPVT.getSimpleVT().SimpleTy) {
13785 case MVT::f16:
13786 return Subtarget->hasVFP2Base();
13787 case MVT::f32:
13788 return Subtarget->hasVFP2Base();
13789 case MVT::f64:
13790 return Subtarget->hasFP64();
13791 case MVT::v4f32:
13792 case MVT::v8f16:
13793 return Subtarget->hasMVEFloatOps();
13794 default:
13795 return false;
13796 }
13797}
13798
13801 const ARMSubtarget *ST) {
13802 // Allow the generic combiner to identify potential bswaps.
13803 if (DCI.isBeforeLegalize())
13804 return SDValue();
13805
13806 // DAG combiner will fold:
13807 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
13808 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
13809 // Other code patterns that can be also be modified have the following form:
13810 // b + ((a << 1) | 510)
13811 // b + ((a << 1) & 510)
13812 // b + ((a << 1) ^ 510)
13813 // b + ((a << 1) + 510)
13814
13815 // Many instructions can perform the shift for free, but it requires both
13816 // the operands to be registers. If c1 << c2 is too large, a mov immediate
13817 // instruction will needed. So, unfold back to the original pattern if:
13818 // - if c1 and c2 are small enough that they don't require mov imms.
13819 // - the user(s) of the node can perform an shl
13820
13821 // No shifted operands for 16-bit instructions.
13822 if (ST->isThumb1Only())
13823 return SDValue();
13824
13825 // Check that all the users could perform the shl themselves.
13826 for (auto *U : N->users()) {
13827 switch(U->getOpcode()) {
13828 default:
13829 return SDValue();
13830 case ISD::SUB:
13831 case ISD::ADD:
13832 case ISD::AND:
13833 case ISD::OR:
13834 case ISD::XOR:
13835 case ISD::SETCC:
13836 case ARMISD::CMP:
13837 // Check that the user isn't already using a constant because there
13838 // aren't any instructions that support an immediate operand and a
13839 // shifted operand.
13840 if (isa<ConstantSDNode>(U->getOperand(0)) ||
13841 isa<ConstantSDNode>(U->getOperand(1)))
13842 return SDValue();
13843
13844 // Check that it's not already using a shift.
13845 if (U->getOperand(0).getOpcode() == ISD::SHL ||
13846 U->getOperand(1).getOpcode() == ISD::SHL)
13847 return SDValue();
13848 break;
13849 }
13850 }
13851
13852 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
13853 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
13854 return SDValue();
13855
13856 if (N->getOperand(0).getOpcode() != ISD::SHL)
13857 return SDValue();
13858
13859 SDValue SHL = N->getOperand(0);
13860
13861 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
13862 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
13863 if (!C1ShlC2 || !C2)
13864 return SDValue();
13865
13866 APInt C2Int = C2->getAPIntValue();
13867 APInt C1Int = C1ShlC2->getAPIntValue();
13868 unsigned C2Width = C2Int.getBitWidth();
13869 if (C2Int.uge(C2Width))
13870 return SDValue();
13871 uint64_t C2Value = C2Int.getZExtValue();
13872
13873 // Check that performing a lshr will not lose any information.
13874 APInt Mask = APInt::getHighBitsSet(C2Width, C2Width - C2Value);
13875 if ((C1Int & Mask) != C1Int)
13876 return SDValue();
13877
13878 // Shift the first constant.
13879 C1Int.lshrInPlace(C2Int);
13880
13881 // The immediates are encoded as an 8-bit value that can be rotated.
13882 auto LargeImm = [](const APInt &Imm) {
13883 unsigned Zeros = Imm.countl_zero() + Imm.countr_zero();
13884 return Imm.getBitWidth() - Zeros > 8;
13885 };
13886
13887 if (LargeImm(C1Int) || LargeImm(C2Int))
13888 return SDValue();
13889
13890 SelectionDAG &DAG = DCI.DAG;
13891 SDLoc dl(N);
13892 SDValue X = SHL.getOperand(0);
13893 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
13894 DAG.getConstant(C1Int, dl, MVT::i32));
13895 // Shift left to compensate for the lshr of C1Int.
13896 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
13897
13898 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
13899 SHL.dump(); N->dump());
13900 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
13901 return Res;
13902}
13903
13904
13905/// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
13906///
13909 const ARMSubtarget *Subtarget) {
13910 SDValue N0 = N->getOperand(0);
13911 SDValue N1 = N->getOperand(1);
13912
13913 // Only works one way, because it needs an immediate operand.
13914 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
13915 return Result;
13916
13917 if (SDValue Result = PerformADDVecReduce(N, DCI.DAG, Subtarget))
13918 return Result;
13919
13920 // First try with the default operand order.
13921 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
13922 return Result;
13923
13924 // If that didn't work, try again with the operands commuted.
13925 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
13926}
13927
13928// Combine (sub 0, (csinc X, Y, CC)) -> (csinv -X, Y, CC)
13929// providing -X is as cheap as X (currently, just a constant).
13931 if (N->getValueType(0) != MVT::i32 || !isNullConstant(N->getOperand(0)))
13932 return SDValue();
13933 SDValue CSINC = N->getOperand(1);
13934 if (CSINC.getOpcode() != ARMISD::CSINC || !CSINC.hasOneUse())
13935 return SDValue();
13936
13938 if (!X)
13939 return SDValue();
13940
13941 return DAG.getNode(ARMISD::CSINV, SDLoc(N), MVT::i32,
13942 DAG.getNode(ISD::SUB, SDLoc(N), MVT::i32, N->getOperand(0),
13943 CSINC.getOperand(0)),
13944 CSINC.getOperand(1), CSINC.getOperand(2),
13945 CSINC.getOperand(3));
13946}
13947
13949 // Free to negate.
13951 return 0;
13952
13953 // Will save one instruction.
13954 if (Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)))
13955 return -1;
13956
13957 // Can freely negate by converting sra <-> srl.
13958 if (Op.getOpcode() == ISD::SRA || Op.getOpcode() == ISD::SRL) {
13959 ConstantSDNode *ShiftAmt = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13960 if (Op.hasOneUse() && ShiftAmt &&
13961 ShiftAmt->getZExtValue() == Op.getValueType().getScalarSizeInBits() - 1)
13962 return 0;
13963 }
13964
13965 // Will have to create sub.
13966 return 1;
13967}
13968
13969// Try to fold
13970//
13971// (neg (cmov X, Y)) -> (cmov (neg X), (neg Y))
13972//
13973// The folding helps cmov to be matched with csneg without generating
13974// redundant neg instruction.
13976 assert(N->getOpcode() == ISD::SUB);
13977 if (!isNullConstant(N->getOperand(0)))
13978 return SDValue();
13979
13980 SDValue CMov = N->getOperand(1);
13981 if (CMov.getOpcode() != ARMISD::CMOV || !CMov->hasOneUse())
13982 return SDValue();
13983
13984 SDValue N0 = CMov.getOperand(0);
13985 SDValue N1 = CMov.getOperand(1);
13986
13987 // Only perform the fold if we actually save something.
13988 if (getNegationCost(N0) + getNegationCost(N1) > 0)
13989 return SDValue();
13990
13991 SDLoc DL(N);
13992 EVT VT = CMov.getValueType();
13993
13994 SDValue N0N = DAG.getNegative(N0, DL, VT);
13995 SDValue N1N = DAG.getNegative(N1, DL, VT);
13996 return DAG.getNode(ARMISD::CMOV, DL, VT, N0N, N1N, CMov.getOperand(2),
13997 CMov.getOperand(3));
13998}
13999
14000/// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
14001///
14004 const ARMSubtarget *Subtarget) {
14005 SDValue N0 = N->getOperand(0);
14006 SDValue N1 = N->getOperand(1);
14007
14008 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
14009 if (N1.getNode()->hasOneUse())
14010 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
14011 return Result;
14012
14013 if (SDValue R = PerformSubCSINCCombine(N, DCI.DAG))
14014 return R;
14015
14016 if (SDValue Val = performNegCMovCombine(N, DCI.DAG))
14017 return Val;
14018
14019 if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector())
14020 return SDValue();
14021
14022 // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x))
14023 // so that we can readily pattern match more mve instructions which can use
14024 // a scalar operand.
14025 SDValue VDup = N->getOperand(1);
14026 if (VDup->getOpcode() != ARMISD::VDUP)
14027 return SDValue();
14028
14029 SDValue VMov = N->getOperand(0);
14030 if (VMov->getOpcode() == ISD::BITCAST)
14031 VMov = VMov->getOperand(0);
14032
14033 if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov))
14034 return SDValue();
14035
14036 SDLoc dl(N);
14037 SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32,
14038 DCI.DAG.getConstant(0, dl, MVT::i32),
14039 VDup->getOperand(0));
14040 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate);
14041}
14042
14043/// PerformVMULCombine
14044/// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
14045/// special multiplier accumulator forwarding.
14046/// vmul d3, d0, d2
14047/// vmla d3, d1, d2
14048/// is faster than
14049/// vadd d3, d0, d1
14050/// vmul d3, d3, d2
14051// However, for (A + B) * (A + B),
14052// vadd d2, d0, d1
14053// vmul d3, d0, d2
14054// vmla d3, d1, d2
14055// is slower than
14056// vadd d2, d0, d1
14057// vmul d3, d2, d2
14060 const ARMSubtarget *Subtarget) {
14061 if (!Subtarget->hasVMLxForwarding())
14062 return SDValue();
14063
14064 SelectionDAG &DAG = DCI.DAG;
14065 SDValue N0 = N->getOperand(0);
14066 SDValue N1 = N->getOperand(1);
14067 unsigned Opcode = N0.getOpcode();
14068 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
14069 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
14070 Opcode = N1.getOpcode();
14071 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
14072 Opcode != ISD::FADD && Opcode != ISD::FSUB)
14073 return SDValue();
14074 std::swap(N0, N1);
14075 }
14076
14077 if (N0 == N1)
14078 return SDValue();
14079
14080 EVT VT = N->getValueType(0);
14081 SDLoc DL(N);
14082 SDValue N00 = N0->getOperand(0);
14083 SDValue N01 = N0->getOperand(1);
14084 return DAG.getNode(Opcode, DL, VT,
14085 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
14086 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
14087}
14088
14090 const ARMSubtarget *Subtarget) {
14091 EVT VT = N->getValueType(0);
14092 if (VT != MVT::v2i64)
14093 return SDValue();
14094
14095 SDValue N0 = N->getOperand(0);
14096 SDValue N1 = N->getOperand(1);
14097
14098 auto IsSignExt = [&](SDValue Op) {
14099 if (Op->getOpcode() != ISD::SIGN_EXTEND_INREG)
14100 return SDValue();
14101 EVT VT = cast<VTSDNode>(Op->getOperand(1))->getVT();
14102 if (VT.getScalarSizeInBits() == 32)
14103 return Op->getOperand(0);
14104 return SDValue();
14105 };
14106 auto IsZeroExt = [&](SDValue Op) {
14107 // Zero extends are a little more awkward. At the point we are matching
14108 // this, we are looking for an AND with a (-1, 0, -1, 0) buildvector mask.
14109 // That might be before of after a bitcast depending on how the and is
14110 // placed. Because this has to look through bitcasts, it is currently only
14111 // supported on LE.
14112 if (!Subtarget->isLittle())
14113 return SDValue();
14114
14115 SDValue And = Op;
14116 if (And->getOpcode() == ISD::BITCAST)
14117 And = And->getOperand(0);
14118 if (And->getOpcode() != ISD::AND)
14119 return SDValue();
14120 SDValue Mask = And->getOperand(1);
14121 if (Mask->getOpcode() == ISD::BITCAST)
14122 Mask = Mask->getOperand(0);
14123
14124 if (Mask->getOpcode() != ISD::BUILD_VECTOR ||
14125 Mask.getValueType() != MVT::v4i32)
14126 return SDValue();
14127 if (isAllOnesConstant(Mask->getOperand(0)) &&
14128 isNullConstant(Mask->getOperand(1)) &&
14129 isAllOnesConstant(Mask->getOperand(2)) &&
14130 isNullConstant(Mask->getOperand(3)))
14131 return And->getOperand(0);
14132 return SDValue();
14133 };
14134
14135 SDLoc dl(N);
14136 if (SDValue Op0 = IsSignExt(N0)) {
14137 if (SDValue Op1 = IsSignExt(N1)) {
14138 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
14139 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
14140 return DAG.getNode(ARMISD::VMULLs, dl, VT, New0a, New1a);
14141 }
14142 }
14143 if (SDValue Op0 = IsZeroExt(N0)) {
14144 if (SDValue Op1 = IsZeroExt(N1)) {
14145 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
14146 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
14147 return DAG.getNode(ARMISD::VMULLu, dl, VT, New0a, New1a);
14148 }
14149 }
14150
14151 return SDValue();
14152}
14153
14156 const ARMSubtarget *Subtarget) {
14157 SelectionDAG &DAG = DCI.DAG;
14158
14159 EVT VT = N->getValueType(0);
14160 if (Subtarget->hasMVEIntegerOps() && VT == MVT::v2i64)
14161 return PerformMVEVMULLCombine(N, DAG, Subtarget);
14162
14163 if (Subtarget->isThumb1Only())
14164 return SDValue();
14165
14166 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14167 return SDValue();
14168
14169 if (VT.is64BitVector() || VT.is128BitVector())
14170 return PerformVMULCombine(N, DCI, Subtarget);
14171 if (VT != MVT::i32)
14172 return SDValue();
14173
14174 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14175 if (!C)
14176 return SDValue();
14177
14178 int64_t MulAmt = C->getSExtValue();
14179 unsigned ShiftAmt = llvm::countr_zero<uint64_t>(MulAmt);
14180
14181 ShiftAmt = ShiftAmt & (32 - 1);
14182 SDValue V = N->getOperand(0);
14183 SDLoc DL(N);
14184
14185 SDValue Res;
14186 MulAmt >>= ShiftAmt;
14187
14188 if (MulAmt >= 0) {
14189 if (llvm::has_single_bit<uint32_t>(MulAmt - 1)) {
14190 // (mul x, 2^N + 1) => (add (shl x, N), x)
14191 Res = DAG.getNode(ISD::ADD, DL, VT,
14192 V,
14193 DAG.getNode(ISD::SHL, DL, VT,
14194 V,
14195 DAG.getConstant(Log2_32(MulAmt - 1), DL,
14196 MVT::i32)));
14197 } else if (llvm::has_single_bit<uint32_t>(MulAmt + 1)) {
14198 // (mul x, 2^N - 1) => (sub (shl x, N), x)
14199 Res = DAG.getNode(ISD::SUB, DL, VT,
14200 DAG.getNode(ISD::SHL, DL, VT,
14201 V,
14202 DAG.getConstant(Log2_32(MulAmt + 1), DL,
14203 MVT::i32)),
14204 V);
14205 } else
14206 return SDValue();
14207 } else {
14208 uint64_t MulAmtAbs = -MulAmt;
14209 if (llvm::has_single_bit<uint32_t>(MulAmtAbs + 1)) {
14210 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
14211 Res = DAG.getNode(ISD::SUB, DL, VT,
14212 V,
14213 DAG.getNode(ISD::SHL, DL, VT,
14214 V,
14215 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
14216 MVT::i32)));
14217 } else if (llvm::has_single_bit<uint32_t>(MulAmtAbs - 1)) {
14218 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
14219 Res = DAG.getNode(ISD::ADD, DL, VT,
14220 V,
14221 DAG.getNode(ISD::SHL, DL, VT,
14222 V,
14223 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
14224 MVT::i32)));
14225 Res = DAG.getNode(ISD::SUB, DL, VT,
14226 DAG.getConstant(0, DL, MVT::i32), Res);
14227 } else
14228 return SDValue();
14229 }
14230
14231 if (ShiftAmt != 0)
14232 Res = DAG.getNode(ISD::SHL, DL, VT,
14233 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
14234
14235 // Do not add new nodes to DAG combiner worklist.
14236 DCI.CombineTo(N, Res, false);
14237 return SDValue();
14238}
14239
14242 const ARMSubtarget *Subtarget) {
14243 // Allow DAGCombine to pattern-match before we touch the canonical form.
14244 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14245 return SDValue();
14246
14247 if (N->getValueType(0) != MVT::i32)
14248 return SDValue();
14249
14250 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14251 if (!N1C)
14252 return SDValue();
14253
14254 uint32_t C1 = (uint32_t)N1C->getZExtValue();
14255 // Don't transform uxtb/uxth.
14256 if (C1 == 255 || C1 == 65535)
14257 return SDValue();
14258
14259 SDNode *N0 = N->getOperand(0).getNode();
14260 if (!N0->hasOneUse())
14261 return SDValue();
14262
14263 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
14264 return SDValue();
14265
14266 bool LeftShift = N0->getOpcode() == ISD::SHL;
14267
14269 if (!N01C)
14270 return SDValue();
14271
14272 uint32_t C2 = (uint32_t)N01C->getZExtValue();
14273 if (!C2 || C2 >= 32)
14274 return SDValue();
14275
14276 // Clear irrelevant bits in the mask.
14277 if (LeftShift)
14278 C1 &= (-1U << C2);
14279 else
14280 C1 &= (-1U >> C2);
14281
14282 SelectionDAG &DAG = DCI.DAG;
14283 SDLoc DL(N);
14284
14285 // We have a pattern of the form "(and (shl x, c2) c1)" or
14286 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
14287 // transform to a pair of shifts, to save materializing c1.
14288
14289 // First pattern: right shift, then mask off leading bits.
14290 // FIXME: Use demanded bits?
14291 if (!LeftShift && isMask_32(C1)) {
14293 if (C2 < C3) {
14294 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
14295 DAG.getConstant(C3 - C2, DL, MVT::i32));
14296 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
14297 DAG.getConstant(C3, DL, MVT::i32));
14298 }
14299 }
14300
14301 // First pattern, reversed: left shift, then mask off trailing bits.
14302 if (LeftShift && isMask_32(~C1)) {
14304 if (C2 < C3) {
14305 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
14306 DAG.getConstant(C3 - C2, DL, MVT::i32));
14307 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
14308 DAG.getConstant(C3, DL, MVT::i32));
14309 }
14310 }
14311
14312 // Second pattern: left shift, then mask off leading bits.
14313 // FIXME: Use demanded bits?
14314 if (LeftShift && isShiftedMask_32(C1)) {
14315 uint32_t Trailing = llvm::countr_zero(C1);
14317 if (Trailing == C2 && C2 + C3 < 32) {
14318 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
14319 DAG.getConstant(C2 + C3, DL, MVT::i32));
14320 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
14321 DAG.getConstant(C3, DL, MVT::i32));
14322 }
14323 }
14324
14325 // Second pattern, reversed: right shift, then mask off trailing bits.
14326 // FIXME: Handle other patterns of known/demanded bits.
14327 if (!LeftShift && isShiftedMask_32(C1)) {
14328 uint32_t Leading = llvm::countl_zero(C1);
14330 if (Leading == C2 && C2 + C3 < 32) {
14331 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
14332 DAG.getConstant(C2 + C3, DL, MVT::i32));
14333 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
14334 DAG.getConstant(C3, DL, MVT::i32));
14335 }
14336 }
14337
14338 // Transform "(and (shl x, c2) c1)" into "(shl (and x, c1>>c2), c2)"
14339 // if "c1 >> c2" is a cheaper immediate than "c1"
14340 if (LeftShift &&
14342
14343 SDValue And = DAG.getNode(ISD::AND, DL, MVT::i32, N0->getOperand(0),
14344 DAG.getConstant(C1 >> C2, DL, MVT::i32));
14345 return DAG.getNode(ISD::SHL, DL, MVT::i32, And,
14346 DAG.getConstant(C2, DL, MVT::i32));
14347 }
14348
14349 return SDValue();
14350}
14351
14354 const ARMSubtarget *Subtarget) {
14355 // Attempt to use immediate-form VBIC
14356 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
14357 SDLoc dl(N);
14358 EVT VT = N->getValueType(0);
14359 SelectionDAG &DAG = DCI.DAG;
14360
14361 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) || VT == MVT::v2i1 ||
14362 VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1)
14363 return SDValue();
14364
14365 APInt SplatBits, SplatUndef;
14366 unsigned SplatBitSize;
14367 bool HasAnyUndefs;
14368 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
14369 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
14370 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
14371 SplatBitSize == 64) {
14372 EVT VbicVT;
14373 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
14374 SplatUndef.getZExtValue(), SplatBitSize,
14375 DAG, dl, VbicVT, VT, OtherModImm);
14376 if (Val.getNode()) {
14377 SDValue Input =
14378 DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VbicVT, N->getOperand(0));
14379 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
14380 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Vbic);
14381 }
14382 }
14383 }
14384
14385 if (!Subtarget->isThumb1Only()) {
14386 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
14387 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
14388 return Result;
14389
14390 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14391 return Result;
14392 }
14393
14394 if (Subtarget->isThumb1Only())
14395 if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
14396 return Result;
14397
14398 return SDValue();
14399}
14400
14401// Try combining OR nodes to SMULWB, SMULWT.
14404 const ARMSubtarget *Subtarget) {
14405 if (!Subtarget->hasV6Ops() ||
14406 (Subtarget->isThumb() &&
14407 (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
14408 return SDValue();
14409
14410 SDValue SRL = OR->getOperand(0);
14411 SDValue SHL = OR->getOperand(1);
14412
14413 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
14414 SRL = OR->getOperand(1);
14415 SHL = OR->getOperand(0);
14416 }
14417 if (!isSRL16(SRL) || !isSHL16(SHL))
14418 return SDValue();
14419
14420 // The first operands to the shifts need to be the two results from the
14421 // same smul_lohi node.
14422 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
14423 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
14424 return SDValue();
14425
14426 SDNode *SMULLOHI = SRL.getOperand(0).getNode();
14427 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
14428 SHL.getOperand(0) != SDValue(SMULLOHI, 1))
14429 return SDValue();
14430
14431 // Now we have:
14432 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
14433 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
14434 // For SMUWB the 16-bit value will signed extended somehow.
14435 // For SMULWT only the SRA is required.
14436 // Check both sides of SMUL_LOHI
14437 SDValue OpS16 = SMULLOHI->getOperand(0);
14438 SDValue OpS32 = SMULLOHI->getOperand(1);
14439
14440 SelectionDAG &DAG = DCI.DAG;
14441 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
14442 OpS16 = OpS32;
14443 OpS32 = SMULLOHI->getOperand(0);
14444 }
14445
14446 SDLoc dl(OR);
14447 unsigned Opcode = 0;
14448 if (isS16(OpS16, DAG))
14449 Opcode = ARMISD::SMULWB;
14450 else if (isSRA16(OpS16)) {
14451 Opcode = ARMISD::SMULWT;
14452 OpS16 = OpS16->getOperand(0);
14453 }
14454 else
14455 return SDValue();
14456
14457 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
14458 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
14459 return SDValue(OR, 0);
14460}
14461
14464 const ARMSubtarget *Subtarget) {
14465 // BFI is only available on V6T2+
14466 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
14467 return SDValue();
14468
14469 EVT VT = N->getValueType(0);
14470 SDValue N0 = N->getOperand(0);
14471 SDValue N1 = N->getOperand(1);
14472 SelectionDAG &DAG = DCI.DAG;
14473 SDLoc DL(N);
14474 // 1) or (and A, mask), val => ARMbfi A, val, mask
14475 // iff (val & mask) == val
14476 //
14477 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
14478 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
14479 // && mask == ~mask2
14480 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
14481 // && ~mask == mask2
14482 // (i.e., copy a bitfield value into another bitfield of the same width)
14483
14484 if (VT != MVT::i32)
14485 return SDValue();
14486
14487 SDValue N00 = N0.getOperand(0);
14488
14489 // The value and the mask need to be constants so we can verify this is
14490 // actually a bitfield set. If the mask is 0xffff, we can do better
14491 // via a movt instruction, so don't use BFI in that case.
14492 SDValue MaskOp = N0.getOperand(1);
14494 if (!MaskC)
14495 return SDValue();
14496 unsigned Mask = MaskC->getZExtValue();
14497 if (Mask == 0xffff)
14498 return SDValue();
14499 SDValue Res;
14500 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
14502 if (N1C) {
14503 unsigned Val = N1C->getZExtValue();
14504 if ((Val & ~Mask) != Val)
14505 return SDValue();
14506
14507 if (ARM::isBitFieldInvertedMask(Mask)) {
14508 Val >>= llvm::countr_zero(~Mask);
14509
14510 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
14511 DAG.getConstant(Val, DL, MVT::i32),
14512 DAG.getConstant(Mask, DL, MVT::i32));
14513
14514 DCI.CombineTo(N, Res, false);
14515 // Return value from the original node to inform the combiner than N is
14516 // now dead.
14517 return SDValue(N, 0);
14518 }
14519 } else if (N1.getOpcode() == ISD::AND) {
14520 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
14522 if (!N11C)
14523 return SDValue();
14524 unsigned Mask2 = N11C->getZExtValue();
14525
14526 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
14527 // as is to match.
14528 if (ARM::isBitFieldInvertedMask(Mask) &&
14529 (Mask == ~Mask2)) {
14530 // The pack halfword instruction works better for masks that fit it,
14531 // so use that when it's available.
14532 if (Subtarget->hasDSP() &&
14533 (Mask == 0xffff || Mask == 0xffff0000))
14534 return SDValue();
14535 // 2a
14536 unsigned amt = llvm::countr_zero(Mask2);
14537 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
14538 DAG.getConstant(amt, DL, MVT::i32));
14539 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
14540 DAG.getConstant(Mask, DL, MVT::i32));
14541 DCI.CombineTo(N, Res, false);
14542 // Return value from the original node to inform the combiner than N is
14543 // now dead.
14544 return SDValue(N, 0);
14545 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
14546 (~Mask == Mask2)) {
14547 // The pack halfword instruction works better for masks that fit it,
14548 // so use that when it's available.
14549 if (Subtarget->hasDSP() &&
14550 (Mask2 == 0xffff || Mask2 == 0xffff0000))
14551 return SDValue();
14552 // 2b
14553 unsigned lsb = llvm::countr_zero(Mask);
14554 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
14555 DAG.getConstant(lsb, DL, MVT::i32));
14556 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
14557 DAG.getConstant(Mask2, DL, MVT::i32));
14558 DCI.CombineTo(N, Res, false);
14559 // Return value from the original node to inform the combiner than N is
14560 // now dead.
14561 return SDValue(N, 0);
14562 }
14563 }
14564
14565 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
14566 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
14568 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
14569 // where lsb(mask) == #shamt and masked bits of B are known zero.
14570 SDValue ShAmt = N00.getOperand(1);
14571 unsigned ShAmtC = ShAmt->getAsZExtVal();
14572 unsigned LSB = llvm::countr_zero(Mask);
14573 if (ShAmtC != LSB)
14574 return SDValue();
14575
14576 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
14577 DAG.getConstant(~Mask, DL, MVT::i32));
14578
14579 DCI.CombineTo(N, Res, false);
14580 // Return value from the original node to inform the combiner than N is
14581 // now dead.
14582 return SDValue(N, 0);
14583 }
14584
14585 return SDValue();
14586}
14587
14588static bool isValidMVECond(unsigned CC, bool IsFloat) {
14589 switch (CC) {
14590 case ARMCC::EQ:
14591 case ARMCC::NE:
14592 case ARMCC::LE:
14593 case ARMCC::GT:
14594 case ARMCC::GE:
14595 case ARMCC::LT:
14596 return true;
14597 case ARMCC::HS:
14598 case ARMCC::HI:
14599 return !IsFloat;
14600 default:
14601 return false;
14602 };
14603}
14604
14606 if (N->getOpcode() == ARMISD::VCMP)
14607 return (ARMCC::CondCodes)N->getConstantOperandVal(2);
14608 else if (N->getOpcode() == ARMISD::VCMPZ)
14609 return (ARMCC::CondCodes)N->getConstantOperandVal(1);
14610 else
14611 llvm_unreachable("Not a VCMP/VCMPZ!");
14612}
14613
14616 return isValidMVECond(CC, N->getOperand(0).getValueType().isFloatingPoint());
14617}
14618
14620 const ARMSubtarget *Subtarget) {
14621 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
14622 // together with predicates
14623 EVT VT = N->getValueType(0);
14624 SDLoc DL(N);
14625 SDValue N0 = N->getOperand(0);
14626 SDValue N1 = N->getOperand(1);
14627
14628 auto IsFreelyInvertable = [&](SDValue V) {
14629 if (V->getOpcode() == ARMISD::VCMP || V->getOpcode() == ARMISD::VCMPZ)
14630 return CanInvertMVEVCMP(V);
14631 return false;
14632 };
14633
14634 // At least one operand must be freely invertable.
14635 if (!(IsFreelyInvertable(N0) || IsFreelyInvertable(N1)))
14636 return SDValue();
14637
14638 SDValue NewN0 = DAG.getLogicalNOT(DL, N0, VT);
14639 SDValue NewN1 = DAG.getLogicalNOT(DL, N1, VT);
14640 SDValue And = DAG.getNode(ISD::AND, DL, VT, NewN0, NewN1);
14641 return DAG.getLogicalNOT(DL, And, VT);
14642}
14643
14644// Try to form a NEON shift-{right, left}-and-insert (VSRI/VSLI) from:
14645// (or (and X, splat (i32 C1)), (srl Y, splat (i32 C2))) -> VSRI X, Y, #C2
14646// (or (and X, splat (i32 C1)), (shl Y, splat (i32 C2))) -> VSLI X, Y, #C2
14647// where C1 is a mask that preserves the bits not written by the shift/insert,
14648// i.e. `C1 == (1 << C2) - 1`.
14650 SDValue ShiftOp, EVT VT,
14651 SDLoc dl) {
14652 // Match (and X, Mask)
14653 if (AndOp.getOpcode() != ISD::AND)
14654 return SDValue();
14655
14656 SDValue X = AndOp.getOperand(0);
14657 SDValue Mask = AndOp.getOperand(1);
14658
14659 ConstantSDNode *MaskC = isConstOrConstSplat(Mask, false, true);
14660 if (!MaskC)
14661 return SDValue();
14662 APInt MaskBits =
14663 MaskC->getAPIntValue().trunc(Mask.getScalarValueSizeInBits());
14664
14665 // Match shift (srl/shl Y, CntVec)
14666 int64_t Cnt = 0;
14667 bool IsShiftRight = false;
14668 SDValue Y;
14669
14670 if (ShiftOp.getOpcode() == ARMISD::VSHRuIMM) {
14671 IsShiftRight = true;
14672 Y = ShiftOp.getOperand(0);
14673 Cnt = ShiftOp.getConstantOperandVal(1);
14674 } else if (ShiftOp.getOpcode() == ARMISD::VSHLIMM) {
14675 Y = ShiftOp.getOperand(0);
14676 Cnt = ShiftOp.getConstantOperandVal(1);
14677 } else {
14678 return SDValue();
14679 }
14680
14681 unsigned ElemBits = VT.getScalarSizeInBits();
14682 APInt RequiredMask = IsShiftRight
14683 ? APInt::getHighBitsSet(ElemBits, (unsigned)Cnt)
14684 : APInt::getLowBitsSet(ElemBits, (unsigned)Cnt);
14685 if (MaskBits != RequiredMask)
14686 return SDValue();
14687
14688 unsigned Opc = IsShiftRight ? ARMISD::VSRIIMM : ARMISD::VSLIIMM;
14689 return DAG.getNode(Opc, dl, VT, X, Y, DAG.getConstant(Cnt, dl, MVT::i32));
14690}
14691
14692/// PerformORCombine - Target-specific dag combine xforms for ISD::OR
14694 const ARMSubtarget *Subtarget) {
14695 // Attempt to use immediate-form VORR
14696 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
14697 SDLoc dl(N);
14698 EVT VT = N->getValueType(0);
14699 SelectionDAG &DAG = DCI.DAG;
14700
14701 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14702 return SDValue();
14703
14704 if (Subtarget->hasMVEIntegerOps() && (VT == MVT::v2i1 || VT == MVT::v4i1 ||
14705 VT == MVT::v8i1 || VT == MVT::v16i1))
14706 return PerformORCombine_i1(N, DAG, Subtarget);
14707
14708 APInt SplatBits, SplatUndef;
14709 unsigned SplatBitSize;
14710 bool HasAnyUndefs;
14711 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
14712 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
14713 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
14714 SplatBitSize == 64) {
14715 EVT VorrVT;
14716 SDValue Val =
14717 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
14718 SplatBitSize, DAG, dl, VorrVT, VT, OtherModImm);
14719 if (Val.getNode()) {
14720 SDValue Input =
14721 DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VorrVT, N->getOperand(0));
14722 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
14723 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Vorr);
14724 }
14725 }
14726 }
14727
14728 if (!Subtarget->isThumb1Only()) {
14729 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
14730 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
14731 return Result;
14732 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
14733 return Result;
14734 }
14735
14736 SDValue N0 = N->getOperand(0);
14737 SDValue N1 = N->getOperand(1);
14738
14739 // (or (and X, C1), (srl Y, C2)) -> VSRI X, Y, #C2
14740 // (or (and X, C1), (shl Y, C2)) -> VSLI X, Y, #C2
14741 if (VT.isVector() &&
14742 ((Subtarget->hasNEON() && DAG.getTargetLoweringInfo().isTypeLegal(VT)) ||
14743 (Subtarget->hasMVEIntegerOps() &&
14744 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32)))) {
14745 if (SDValue ShiftInsert =
14746 PerformORCombineToShiftInsert(DAG, N0, N1, VT, dl))
14747 return ShiftInsert;
14748
14749 if (SDValue ShiftInsert =
14750 PerformORCombineToShiftInsert(DAG, N1, N0, VT, dl))
14751 return ShiftInsert;
14752 }
14753
14754 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
14755 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
14757
14758 // The code below optimizes (or (and X, Y), Z).
14759 // The AND operand needs to have a single user to make these optimizations
14760 // profitable.
14761 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
14762 return SDValue();
14763
14764 APInt SplatUndef;
14765 unsigned SplatBitSize;
14766 bool HasAnyUndefs;
14767
14768 APInt SplatBits0, SplatBits1;
14771 // Ensure that the second operand of both ands are constants
14772 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
14773 HasAnyUndefs) && !HasAnyUndefs) {
14774 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
14775 HasAnyUndefs) && !HasAnyUndefs) {
14776 // Ensure that the bit width of the constants are the same and that
14777 // the splat arguments are logical inverses as per the pattern we
14778 // are trying to simplify.
14779 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
14780 SplatBits0 == ~SplatBits1) {
14781 // Canonicalize the vector type to make instruction selection
14782 // simpler.
14783 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
14784 SDValue Mask = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl,
14785 CanonicalVT, N0->getOperand(1));
14786 SDValue LHS = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl,
14787 CanonicalVT, N0->getOperand(0));
14788 SDValue RHS = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl,
14789 CanonicalVT, N1->getOperand(0));
14790 SDValue Result =
14791 DAG.getNode(ARMISD::VBSP, dl, CanonicalVT, Mask, LHS, RHS);
14792 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Result);
14793 }
14794 }
14795 }
14796 }
14797
14798 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
14799 // reasonable.
14800 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
14801 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
14802 return Res;
14803 }
14804
14805 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14806 return Result;
14807
14808 // (or x, (csinc 0, 0, cc)) -> (csinc x, 0, cc)
14809 // providing that the x is 0 or 1.
14810 SDValue CSINC = N1;
14811 SDValue Other = N0;
14812 if (CSINC.getOpcode() != ARMISD::CSINC)
14813 std::swap(CSINC, Other);
14814 if (CSINC.getOpcode() == ARMISD::CSINC &&
14815 isNullConstant(CSINC.getOperand(0)) &&
14816 isNullConstant(CSINC.getOperand(1)) &&
14818 return DAG.getNode(ARMISD::CSINC, dl, VT, Other, CSINC.getOperand(1),
14819 CSINC.getOperand(2), CSINC.getOperand(3));
14820
14821 return SDValue();
14822}
14823
14826 const ARMSubtarget *Subtarget) {
14827 EVT VT = N->getValueType(0);
14828 SelectionDAG &DAG = DCI.DAG;
14829
14830 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14831 return SDValue();
14832
14833 if (!Subtarget->isThumb1Only()) {
14834 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
14835 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
14836 return Result;
14837
14838 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14839 return Result;
14840 }
14841
14842 if (Subtarget->hasMVEIntegerOps()) {
14843 // fold (xor(vcmp/z, 1)) into a vcmp with the opposite condition.
14844 SDValue N0 = N->getOperand(0);
14845 SDValue N1 = N->getOperand(1);
14846 const TargetLowering *TLI = Subtarget->getTargetLowering();
14847 if (TLI->isConstTrueVal(N1) &&
14848 (N0->getOpcode() == ARMISD::VCMP || N0->getOpcode() == ARMISD::VCMPZ)) {
14849 if (CanInvertMVEVCMP(N0)) {
14850 SDLoc DL(N0);
14852
14854 Ops.push_back(N0->getOperand(0));
14855 if (N0->getOpcode() == ARMISD::VCMP)
14856 Ops.push_back(N0->getOperand(1));
14857 Ops.push_back(DAG.getConstant(CC, DL, MVT::i32));
14858 return DAG.getNode(N0->getOpcode(), DL, N0->getValueType(0), Ops);
14859 }
14860 }
14861 }
14862
14863 return SDValue();
14864}
14865
14866// ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
14867// and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
14868// their position in "to" (Rd).
14869static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
14870 assert(N->getOpcode() == ARMISD::BFI);
14871
14872 SDValue From = N->getOperand(1);
14873 ToMask = ~N->getConstantOperandAPInt(2);
14874 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.popcount());
14875
14876 // If the Base came from a SHR #C, we can deduce that it is really testing bit
14877 // #C in the base of the SHR.
14878 if (From->getOpcode() == ISD::SRL &&
14879 isa<ConstantSDNode>(From->getOperand(1))) {
14880 APInt Shift = From->getConstantOperandAPInt(1);
14881 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
14882 FromMask <<= Shift.getLimitedValue(31);
14883 From = From->getOperand(0);
14884 }
14885
14886 return From;
14887}
14888
14889// If A and B contain one contiguous set of bits, does A | B == A . B?
14890//
14891// Neither A nor B must be zero.
14892static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
14893 unsigned LastActiveBitInA = A.countr_zero();
14894 unsigned FirstActiveBitInB = B.getBitWidth() - B.countl_zero() - 1;
14895 return LastActiveBitInA - 1 == FirstActiveBitInB;
14896}
14897
14899 // We have a BFI in N. Find a BFI it can combine with, if one exists.
14900 APInt ToMask, FromMask;
14901 SDValue From = ParseBFI(N, ToMask, FromMask);
14902 SDValue To = N->getOperand(0);
14903
14904 SDValue V = To;
14905 if (V.getOpcode() != ARMISD::BFI)
14906 return SDValue();
14907
14908 APInt NewToMask, NewFromMask;
14909 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
14910 if (NewFrom != From)
14911 return SDValue();
14912
14913 // Do the written bits conflict with any we've seen so far?
14914 if ((NewToMask & ToMask).getBoolValue())
14915 // Conflicting bits.
14916 return SDValue();
14917
14918 // Are the new bits contiguous when combined with the old bits?
14919 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
14920 BitsProperlyConcatenate(FromMask, NewFromMask))
14921 return V;
14922 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
14923 BitsProperlyConcatenate(NewFromMask, FromMask))
14924 return V;
14925
14926 return SDValue();
14927}
14928
14930 SDValue N0 = N->getOperand(0);
14931 SDValue N1 = N->getOperand(1);
14932
14933 if (N1.getOpcode() == ISD::AND) {
14934 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
14935 // the bits being cleared by the AND are not demanded by the BFI.
14937 if (!N11C)
14938 return SDValue();
14939 unsigned InvMask = N->getConstantOperandVal(2);
14940 unsigned LSB = llvm::countr_zero(~InvMask);
14941 unsigned Width = llvm::bit_width<unsigned>(~InvMask) - LSB;
14942 assert(Width <
14943 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
14944 "undefined behavior");
14945 unsigned Mask = (1u << Width) - 1;
14946 unsigned Mask2 = N11C->getZExtValue();
14947 if ((Mask & (~Mask2)) == 0)
14948 return DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
14949 N->getOperand(0), N1.getOperand(0), N->getOperand(2));
14950 return SDValue();
14951 }
14952
14953 // Look for another BFI to combine with.
14954 if (SDValue CombineBFI = FindBFIToCombineWith(N)) {
14955 // We've found a BFI.
14956 APInt ToMask1, FromMask1;
14957 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
14958
14959 APInt ToMask2, FromMask2;
14960 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
14961 assert(From1 == From2);
14962 (void)From2;
14963
14964 // Create a new BFI, combining the two together.
14965 APInt NewFromMask = FromMask1 | FromMask2;
14966 APInt NewToMask = ToMask1 | ToMask2;
14967
14968 EVT VT = N->getValueType(0);
14969 SDLoc dl(N);
14970
14971 if (NewFromMask[0] == 0)
14972 From1 = DAG.getNode(ISD::SRL, dl, VT, From1,
14973 DAG.getConstant(NewFromMask.countr_zero(), dl, VT));
14974 return DAG.getNode(ARMISD::BFI, dl, VT, CombineBFI.getOperand(0), From1,
14975 DAG.getConstant(~NewToMask, dl, VT));
14976 }
14977
14978 // Reassociate BFI(BFI (A, B, M1), C, M2) to BFI(BFI (A, C, M2), B, M1) so
14979 // that lower bit insertions are performed first, providing that M1 and M2
14980 // do no overlap. This can allow multiple BFI instructions to be combined
14981 // together by the other folds above.
14982 if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
14983 APInt ToMask1 = ~N->getConstantOperandAPInt(2);
14984 APInt ToMask2 = ~N0.getConstantOperandAPInt(2);
14985
14986 if (!N0.hasOneUse() || (ToMask1 & ToMask2) != 0 ||
14987 ToMask1.countl_zero() < ToMask2.countl_zero())
14988 return SDValue();
14989
14990 EVT VT = N->getValueType(0);
14991 SDLoc dl(N);
14992 SDValue BFI1 = DAG.getNode(ARMISD::BFI, dl, VT, N0.getOperand(0),
14993 N->getOperand(1), N->getOperand(2));
14994 return DAG.getNode(ARMISD::BFI, dl, VT, BFI1, N0.getOperand(1),
14995 N0.getOperand(2));
14996 }
14997
14998 return SDValue();
14999}
15000
15001// Check that N is CMPZ(CSINC(0, 0, CC, X)),
15002// or CMPZ(CMOV(1, 0, CC, X))
15003// return X if valid.
15005 if (Cmp->getOpcode() != ARMISD::CMPZ || !isNullConstant(Cmp->getOperand(1)))
15006 return SDValue();
15007 SDValue CSInc = Cmp->getOperand(0);
15008
15009 // Ignore any `And 1` nodes that may not yet have been removed. We are
15010 // looking for a value that produces 1/0, so these have no effect on the
15011 // code.
15012 while (CSInc.getOpcode() == ISD::AND &&
15013 isa<ConstantSDNode>(CSInc.getOperand(1)) &&
15014 CSInc.getConstantOperandVal(1) == 1 && CSInc->hasOneUse())
15015 CSInc = CSInc.getOperand(0);
15016
15017 if (CSInc.getOpcode() == ARMISD::CSINC &&
15018 isNullConstant(CSInc.getOperand(0)) &&
15019 isNullConstant(CSInc.getOperand(1)) && CSInc->hasOneUse()) {
15021 return CSInc.getOperand(3);
15022 }
15023 if (CSInc.getOpcode() == ARMISD::CMOV && isOneConstant(CSInc.getOperand(0)) &&
15024 isNullConstant(CSInc.getOperand(1)) && CSInc->hasOneUse()) {
15026 return CSInc.getOperand(3);
15027 }
15028 if (CSInc.getOpcode() == ARMISD::CMOV && isOneConstant(CSInc.getOperand(1)) &&
15029 isNullConstant(CSInc.getOperand(0)) && CSInc->hasOneUse()) {
15032 return CSInc.getOperand(3);
15033 }
15034 return SDValue();
15035}
15036
15038 // Given CMPZ(CSINC(C, 0, 0, EQ), 0), we can just use C directly. As in
15039 // t92: flags = ARMISD::CMPZ t74, 0
15040 // t93: i32 = ARMISD::CSINC 0, 0, 1, t92
15041 // t96: flags = ARMISD::CMPZ t93, 0
15042 // t114: i32 = ARMISD::CSINV 0, 0, 0, t96
15044 if (SDValue C = IsCMPZCSINC(N, Cond))
15045 if (Cond == ARMCC::EQ)
15046 return C;
15047 return SDValue();
15048}
15049
15051 // Fold away an unnecessary CMPZ/CSINC
15052 // CSXYZ A, B, C1 (CMPZ (CSINC 0, 0, C2, D), 0) ->
15053 // if C1==EQ -> CSXYZ A, B, C2, D
15054 // if C1==NE -> CSXYZ A, B, NOT(C2), D
15056 if (SDValue C = IsCMPZCSINC(N->getOperand(3).getNode(), Cond)) {
15057 if (N->getConstantOperandVal(2) == ARMCC::EQ)
15058 return DAG.getNode(N->getOpcode(), SDLoc(N), MVT::i32, N->getOperand(0),
15059 N->getOperand(1),
15060 DAG.getConstant(Cond, SDLoc(N), MVT::i32), C);
15061 if (N->getConstantOperandVal(2) == ARMCC::NE)
15062 return DAG.getNode(
15063 N->getOpcode(), SDLoc(N), MVT::i32, N->getOperand(0),
15064 N->getOperand(1),
15066 }
15067 return SDValue();
15068}
15069
15070/// PerformVMOVRRDCombine - Target-specific dag combine xforms for
15071/// ARMISD::VMOVRRD.
15074 const ARMSubtarget *Subtarget) {
15075 // vmovrrd(vmovdrr x, y) -> x,y
15076 SDValue InDouble = N->getOperand(0);
15077 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
15078 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
15079
15080 // vmovrrd(load f64) -> (load i32), (load i32)
15081 SDNode *InNode = InDouble.getNode();
15082 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
15083 InNode->getValueType(0) == MVT::f64 &&
15084 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
15085 !cast<LoadSDNode>(InNode)->isVolatile()) {
15086 // TODO: Should this be done for non-FrameIndex operands?
15087 LoadSDNode *LD = cast<LoadSDNode>(InNode);
15088
15089 SelectionDAG &DAG = DCI.DAG;
15090 SDLoc DL(LD);
15091 SDValue BasePtr = LD->getBasePtr();
15092 SDValue NewLD1 =
15093 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
15094 LD->getAlign(), LD->getMemOperand()->getFlags());
15095
15096 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
15097 DAG.getConstant(4, DL, MVT::i32));
15098
15099 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
15100 LD->getPointerInfo().getWithOffset(4),
15101 commonAlignment(LD->getAlign(), 4),
15102 LD->getMemOperand()->getFlags());
15103
15104 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
15105 if (DCI.DAG.getDataLayout().isBigEndian())
15106 std::swap (NewLD1, NewLD2);
15107 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
15108 return Result;
15109 }
15110
15111 // VMOVRRD(extract(..(build_vector(a, b, c, d)))) -> a,b or c,d
15112 // VMOVRRD(extract(insert_vector(insert_vector(.., a, l1), b, l2))) -> a,b
15113 if (InDouble.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15114 isa<ConstantSDNode>(InDouble.getOperand(1))) {
15115 SDValue BV = InDouble.getOperand(0);
15116 // Look up through any nop bitcasts and vector_reg_casts. bitcasts may
15117 // change lane order under big endian.
15118 bool BVSwap = BV.getOpcode() == ISD::BITCAST;
15119 while (
15120 (BV.getOpcode() == ISD::BITCAST ||
15121 BV.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
15122 (BV.getValueType() == MVT::v2f64 || BV.getValueType() == MVT::v2i64)) {
15123 BVSwap = BV.getOpcode() == ISD::BITCAST;
15124 BV = BV.getOperand(0);
15125 }
15126 if (BV.getValueType() != MVT::v4i32)
15127 return SDValue();
15128
15129 // Handle buildvectors, pulling out the correct lane depending on
15130 // endianness.
15131 unsigned Offset = InDouble.getConstantOperandVal(1) == 1 ? 2 : 0;
15132 if (BV.getOpcode() == ISD::BUILD_VECTOR) {
15133 SDValue Op0 = BV.getOperand(Offset);
15134 SDValue Op1 = BV.getOperand(Offset + 1);
15135 if (!Subtarget->isLittle() && BVSwap)
15136 std::swap(Op0, Op1);
15137
15138 return DCI.DAG.getMergeValues({Op0, Op1}, SDLoc(N));
15139 }
15140
15141 // A chain of insert_vectors, grabbing the correct value of the chain of
15142 // inserts.
15143 SDValue Op0, Op1;
15144 while (BV.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15145 if (isa<ConstantSDNode>(BV.getOperand(2))) {
15146 if (BV.getConstantOperandVal(2) == Offset && !Op0)
15147 Op0 = BV.getOperand(1);
15148 if (BV.getConstantOperandVal(2) == Offset + 1 && !Op1)
15149 Op1 = BV.getOperand(1);
15150 }
15151 BV = BV.getOperand(0);
15152 }
15153 if (!Subtarget->isLittle() && BVSwap)
15154 std::swap(Op0, Op1);
15155 if (Op0 && Op1)
15156 return DCI.DAG.getMergeValues({Op0, Op1}, SDLoc(N));
15157 }
15158
15159 return SDValue();
15160}
15161
15162/// PerformVMOVDRRCombine - Target-specific dag combine xforms for
15163/// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
15165 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
15166 SDValue Op0 = N->getOperand(0);
15167 SDValue Op1 = N->getOperand(1);
15168 if (Op0.getOpcode() == ISD::BITCAST)
15169 Op0 = Op0.getOperand(0);
15170 if (Op1.getOpcode() == ISD::BITCAST)
15171 Op1 = Op1.getOperand(0);
15172 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
15173 Op0.getNode() == Op1.getNode() &&
15174 Op0.getResNo() == 0 && Op1.getResNo() == 1)
15175 return DAG.getNode(ISD::BITCAST, SDLoc(N),
15176 N->getValueType(0), Op0.getOperand(0));
15177 return SDValue();
15178}
15179
15182 SDValue Op0 = N->getOperand(0);
15183
15184 // VMOVhr (VMOVrh (X)) -> X
15185 if (Op0->getOpcode() == ARMISD::VMOVrh)
15186 return Op0->getOperand(0);
15187
15188 // FullFP16: half values are passed in S-registers, and we don't
15189 // need any of the bitcast and moves:
15190 //
15191 // t2: f32,ch1,gl1? = CopyFromReg ch, Register:f32 %0, gl?
15192 // t5: i32 = bitcast t2
15193 // t18: f16 = ARMISD::VMOVhr t5
15194 // =>
15195 // tN: f16,ch2,gl2? = CopyFromReg ch, Register::f32 %0, gl?
15196 if (Op0->getOpcode() == ISD::BITCAST) {
15197 SDValue Copy = Op0->getOperand(0);
15198 if (Copy.getValueType() == MVT::f32 &&
15199 Copy->getOpcode() == ISD::CopyFromReg) {
15200 bool HasGlue = Copy->getNumOperands() == 3;
15201 SDValue Ops[] = {Copy->getOperand(0), Copy->getOperand(1),
15202 HasGlue ? Copy->getOperand(2) : SDValue()};
15203 EVT OutTys[] = {N->getValueType(0), MVT::Other, MVT::Glue};
15204 SDValue NewCopy =
15206 DCI.DAG.getVTList(ArrayRef(OutTys, HasGlue ? 3 : 2)),
15207 ArrayRef(Ops, HasGlue ? 3 : 2));
15208
15209 // Update Users, Chains, and Potential Glue.
15210 DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), NewCopy.getValue(0));
15211 DCI.DAG.ReplaceAllUsesOfValueWith(Copy.getValue(1), NewCopy.getValue(1));
15212 if (HasGlue)
15213 DCI.DAG.ReplaceAllUsesOfValueWith(Copy.getValue(2),
15214 NewCopy.getValue(2));
15215
15216 return NewCopy;
15217 }
15218 }
15219
15220 // fold (VMOVhr (load x)) -> (load (f16*)x)
15221 if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(Op0)) {
15222 if (LN0->hasOneUse() && LN0->isUnindexed() &&
15223 LN0->getMemoryVT() == MVT::i16) {
15224 SDValue Load =
15225 DCI.DAG.getLoad(N->getValueType(0), SDLoc(N), LN0->getChain(),
15226 LN0->getBasePtr(), LN0->getMemOperand());
15227 DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
15228 DCI.DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Load.getValue(1));
15229 return Load;
15230 }
15231 }
15232
15233 // Only the bottom 16 bits of the source register are used.
15234 APInt DemandedMask = APInt::getLowBitsSet(32, 16);
15236 if (TLI.SimplifyDemandedBits(Op0, DemandedMask, DCI))
15237 return SDValue(N, 0);
15238
15239 return SDValue();
15240}
15241
15243 SDValue N0 = N->getOperand(0);
15244 EVT VT = N->getValueType(0);
15245
15246 // fold (VMOVrh (fpconst x)) -> const x
15248 APFloat V = C->getValueAPF();
15249 return DAG.getConstant(V.bitcastToAPInt().getZExtValue(), SDLoc(N), VT);
15250 }
15251
15252 // fold (VMOVrh (load x)) -> (zextload (i16*)x)
15253 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
15254 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
15255
15256 SDValue Load =
15257 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, LN0->getChain(),
15258 LN0->getBasePtr(), MVT::i16, LN0->getMemOperand());
15259 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
15260 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
15261 return Load;
15262 }
15263
15264 // Fold VMOVrh(extract(x, n)) -> vgetlaneu(x, n)
15265 if (N0->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15267 return DAG.getNode(ARMISD::VGETLANEu, SDLoc(N), VT, N0->getOperand(0),
15268 N0->getOperand(1));
15269
15270 return SDValue();
15271}
15272
15274 SDValue Op0 = N->getOperand(0);
15275 if (Op0->getOpcode() == ARMISD::VMOVsr)
15276 return Op0->getOperand(0);
15277 return SDValue();
15278}
15279
15280/// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
15281/// are normal, non-volatile loads. If so, it is profitable to bitcast an
15282/// i64 vector to have f64 elements, since the value can then be loaded
15283/// directly into a VFP register.
15285 unsigned NumElts = N->getValueType(0).getVectorNumElements();
15286 for (unsigned i = 0; i < NumElts; ++i) {
15287 SDNode *Elt = N->getOperand(i).getNode();
15288 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
15289 return true;
15290 }
15291 return false;
15292}
15293
15294/// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
15295/// ISD::BUILD_VECTOR.
15298 const ARMSubtarget *Subtarget) {
15299 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
15300 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
15301 // into a pair of GPRs, which is fine when the value is used as a scalar,
15302 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
15303 SelectionDAG &DAG = DCI.DAG;
15304 if (N->getNumOperands() == 2)
15305 if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
15306 return RV;
15307
15308 // Load i64 elements as f64 values so that type legalization does not split
15309 // them up into i32 values.
15310 EVT VT = N->getValueType(0);
15311 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
15312 return SDValue();
15313 SDLoc dl(N);
15315 unsigned NumElts = VT.getVectorNumElements();
15316 for (unsigned i = 0; i < NumElts; ++i) {
15317 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
15318 Ops.push_back(V);
15319 // Make the DAGCombiner fold the bitcast.
15320 DCI.AddToWorklist(V.getNode());
15321 }
15322 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
15323 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
15324 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
15325}
15326
15329 const ARMSubtarget *Subtarget) {
15330 // Type legalization splits a wide load into consecutive legal loads. Combine
15331 // each group used by a legal VECTOR_DEINTERLEAVE into a structured load.
15333 return SDValue();
15334
15335 unsigned NumParts = N->getNumOperands();
15337 return SDValue();
15338
15339 if (NumParts == 3 && Subtarget->hasMVEIntegerOps())
15340 return SDValue();
15341
15342 EVT SubVecTy = N->getValueType(0);
15343 if (Subtarget->hasNEON() && !SubVecTy.is64BitVector() &&
15344 !SubVecTy.is128BitVector())
15345 return SDValue();
15346 if (Subtarget->hasMVEIntegerOps() && !SubVecTy.is128BitVector())
15347 return SDValue();
15348 unsigned EltBits = SubVecTy.getScalarSizeInBits();
15349 if (EltBits != 8 && EltBits != 16 && EltBits != 32)
15350 return SDValue();
15351
15353 for (const SDValue &Operand : N->op_values()) {
15354 auto *Load = dyn_cast<LoadSDNode>(Operand);
15355 if (!Load || !Operand.hasOneUse())
15356 return SDValue();
15357 Loads.push_back(Load);
15358 }
15359
15360 LoadSDNode *BaseLoad = Loads[0];
15361 if (Subtarget->hasMVEIntegerOps() && BaseLoad->getAlign() < EltBits / 8)
15362 return SDValue();
15363 unsigned Bytes = SubVecTy.getStoreSize().getFixedValue();
15364 for (auto [Idx, Load] : enumerate(Loads)) {
15365 if (!DAG.areNonVolatileConsecutiveLoads(Load, BaseLoad, Bytes, Idx))
15366 return SDValue();
15367 }
15368
15369 SDLoc DL(N);
15370 EVT MemVT =
15371 EVT::getVectorVT(*DAG.getContext(), SubVecTy.getVectorElementType(),
15372 SubVecTy.getVectorElementCount() * NumParts);
15374 MachineMemOperand *MMO =
15375 MF.getMachineMemOperand(BaseLoad->getMemOperand(), 0, NumParts * Bytes);
15376
15378 ResVTs.push_back(MVT::Other);
15379
15380 SmallVector<SDValue> NewLdOps;
15381 NewLdOps.push_back(BaseLoad->getChain());
15382 Intrinsic::ID IID = 0;
15383 static constexpr Intrinsic::ID NEONLoads[] = {Intrinsic::arm_neon_vld2,
15384 Intrinsic::arm_neon_vld3,
15385 Intrinsic::arm_neon_vld4};
15386 if (Subtarget->hasNEON())
15387 IID = NEONLoads[NumParts - 2];
15388 else
15389 IID = NumParts == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q;
15390
15391 NewLdOps.push_back(DAG.getTargetConstant(IID, DL, MVT::i64));
15392 NewLdOps.push_back(BaseLoad->getBasePtr());
15393 // We can now generate a structured load!
15394 SDValue NewLoad = DAG.getMemIntrinsicNode(
15395 ISD::INTRINSIC_W_CHAIN, DL, DAG.getVTList(ResVTs), NewLdOps, MemVT, MMO);
15396
15398 for (unsigned I = 0; I != NumParts; ++I)
15399 ResOps.push_back(NewLoad.getValue(I));
15400
15401 // Preserve the memory ordering of each original load with the new load.
15402 for (LoadSDNode *Load : Loads)
15404 NewLoad.getValue(NumParts));
15405 return DCI.CombineTo(N, ResOps, false);
15406}
15407
15408// Combine a deinterleave of adjacent subvectors from one load into a
15409// structured NEON load.
15410static SDValue
15413 const ARMSubtarget *Subtarget) {
15414 if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps())
15415 return SDValue();
15416
15418 Subtarget))
15419 return Res;
15420
15421 if (!DCI.isBeforeLegalize())
15422 return SDValue();
15423
15424 SelectionDAG &DAG = DCI.DAG;
15425 unsigned NumParts = N->getNumOperands();
15426 if (NumParts != 2 && NumParts != 3 && NumParts != 4)
15427 return SDValue();
15428
15429 if (NumParts == 3 && Subtarget->hasMVEIntegerOps())
15430 return SDValue();
15431
15432 EVT SubVecTy = N->getValueType(0);
15433
15434 if (Subtarget->hasNEON() && !SubVecTy.is64BitVector() &&
15435 !SubVecTy.is128BitVector())
15436 return SDValue();
15437 if (Subtarget->hasMVEIntegerOps() && !SubVecTy.is128BitVector())
15438 return SDValue();
15439 unsigned EltBits = SubVecTy.getScalarSizeInBits();
15440 if (EltBits != 8 && EltBits != 16 && EltBits != 32)
15441 return SDValue();
15442
15443 // Make sure each input operand is the correct extract_subvector of the same
15444 // wider vector.
15445 unsigned MinNumElements = SubVecTy.getVectorMinNumElements();
15446 SDValue Op0 = N->getOperand(0);
15447 for (unsigned I = 0; I < NumParts; I++) {
15448 SDValue OpI = N->getOperand(I);
15449 if (!OpI.hasOneUse() || OpI.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
15450 OpI.getOperand(0) != Op0.getOperand(0))
15451 return SDValue();
15452 if (OpI.getConstantOperandVal(1) != (I * MinNumElements))
15453 return SDValue();
15454 }
15455
15456 SDValue WideVec = Op0.getOperand(0);
15457 SDLoc DL(N);
15458
15460 ResVTs.push_back(MVT::Other);
15461 SDVTList ResVTList = DAG.getVTList(ResVTs);
15462 auto *Load = dyn_cast<LoadSDNode>(WideVec);
15463 if (!Load || !Load->hasNUsesOfValue(NumParts, 0) || !Load->isSimple() ||
15464 !ISD::isNormalLoad(Load) || !Load->getOffset().isUndef())
15465 return SDValue();
15466 if (Subtarget->hasMVEIntegerOps() && Load->getAlign() < EltBits / 8)
15467 return SDValue();
15468
15469 static constexpr Intrinsic::ID NEONLoads[] = {Intrinsic::arm_neon_vld2,
15470 Intrinsic::arm_neon_vld3,
15471 Intrinsic::arm_neon_vld4};
15472 SmallVector<SDValue> NewLdOps;
15473 Intrinsic::ID IID = 0;
15474 NewLdOps.push_back(Load->getChain());
15475 if (Subtarget->hasNEON())
15476 IID = NEONLoads[NumParts - 2];
15477 else
15478 IID = NumParts == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q;
15479 NewLdOps.push_back(DAG.getTargetConstant(IID, DL, MVT::i64));
15480
15481 NewLdOps.push_back(Load->getBasePtr());
15482
15483 // We can now generate a structured load!
15484 SDValue Res =
15485 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, ResVTList, NewLdOps,
15486 Load->getMemoryVT(), Load->getMemOperand());
15487
15489 for (unsigned Idx = 0; Idx < NumParts; Idx++)
15490 ResOps[Idx] = Res.getValue(Idx);
15491
15492 // Preserve the original load's memory ordering with the new load.
15494 return DCI.CombineTo(N, ResOps, false);
15495}
15496
15497/// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
15498static SDValue
15500 SelectionDAG &DAG = DCI.DAG;
15501 EVT VT = N->getValueType(0);
15502
15503 // Fold buildvector(extractelt(bitcast(build_vector(a,b,_,_))),
15504 // extractelt(bitcast(build_vector(_,_,c,d))))
15505 // -> bitcast(build_vector(a,b,c,d))
15506 if (VT.getScalarSizeInBits() == 64 && N->getNumOperands() == 2) {
15507 auto IsExtractFromBuildVec = [](SDValue V, SDValue &BV, int64_t &Lane) {
15508 if (!sd_match(V, m_ExtractElt(m_Value(BV), m_ConstInt(Lane))))
15509 return false;
15510 while (BV.getOpcode() == ISD::BITCAST)
15511 BV = BV.getOperand(0);
15512 return BV.getOpcode() == ARMISD::BUILD_VECTOR &&
15513 BV.getNumOperands() == 4 &&
15514 BV.getValueType().getScalarSizeInBits() == 32;
15515 };
15516 SDValue BV1, BV2;
15517 int64_t Lane1, Lane2;
15518 if (IsExtractFromBuildVec(N->getOperand(0), BV1, Lane1) &&
15519 IsExtractFromBuildVec(N->getOperand(1), BV2, Lane2))
15520 return DAG.getBitcast(
15521 VT, DAG.getNode(
15522 ARMISD::BUILD_VECTOR, N, MVT::v4f32,
15523 DAG.getBitcast(MVT::f32, BV1->getOperand(Lane1 * 2 + 0)),
15524 DAG.getBitcast(MVT::f32, BV1->getOperand(Lane1 * 2 + 1)),
15525 DAG.getBitcast(MVT::f32, BV2->getOperand(Lane2 * 2 + 0)),
15526 DAG.getBitcast(MVT::f32, BV2->getOperand(Lane2 * 2 + 1))));
15527 }
15528
15529 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
15530 // At that time, we may have inserted bitcasts from integer to float.
15531 // If these bitcasts have survived DAGCombine, change the lowering of this
15532 // BUILD_VECTOR in something more vector friendly, i.e., that does not
15533 // force to use floating point types.
15534
15535 // Make sure we can change the type of the vector.
15536 // This is possible iff:
15537 // 1. The vector is only used in a bitcast to a integer type. I.e.,
15538 // 1.1. Vector is used only once.
15539 // 1.2. Use is a bit convert to an integer type.
15540 // 2. The size of its operands are 32-bits (64-bits are not legal).
15541 EVT EltVT = VT.getVectorElementType();
15542
15543 // Check 1.1. and 2.
15544 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
15545 return SDValue();
15546
15547 // By construction, the input type must be float.
15548 assert(EltVT == MVT::f32 && "Unexpected type!");
15549
15550 // Check 1.2.
15551 SDNode *Use = *N->user_begin();
15552 if (Use->getOpcode() != ISD::BITCAST ||
15553 Use->getValueType(0).isFloatingPoint())
15554 return SDValue();
15555
15556 // Check profitability.
15557 // Model is, if more than half of the relevant operands are bitcast from
15558 // i32, turn the build_vector into a sequence of insert_vector_elt.
15559 // Relevant operands are everything that is not statically
15560 // (i.e., at compile time) bitcasted.
15561 unsigned NumOfBitCastedElts = 0;
15562 unsigned NumElts = VT.getVectorNumElements();
15563 unsigned NumOfRelevantElts = NumElts;
15564 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
15565 SDValue Elt = N->getOperand(Idx);
15566 if (Elt->getOpcode() == ISD::BITCAST) {
15567 // Assume only bit cast to i32 will go away.
15568 if (Elt->getOperand(0).getValueType() == MVT::i32)
15569 ++NumOfBitCastedElts;
15570 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
15571 // Constants are statically casted, thus do not count them as
15572 // relevant operands.
15573 --NumOfRelevantElts;
15574 }
15575
15576 // Check if more than half of the elements require a non-free bitcast.
15577 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
15578 return SDValue();
15579
15580 // Create the new vector type.
15581 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
15582 // Check if the type is legal.
15584 if (!TLI.isTypeLegal(VecVT))
15585 return SDValue();
15586
15587 // Combine:
15588 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
15589 // => BITCAST INSERT_VECTOR_ELT
15590 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
15591 // (BITCAST EN), N.
15592 SDValue Vec = DAG.getUNDEF(VecVT);
15593 SDLoc dl(N);
15594 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
15595 SDValue V = N->getOperand(Idx);
15596 if (V.isUndef())
15597 continue;
15598 if (V.getOpcode() == ISD::BITCAST &&
15599 V->getOperand(0).getValueType() == MVT::i32)
15600 // Fold obvious case.
15601 V = V.getOperand(0);
15602 else {
15603 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
15604 // Make the DAGCombiner fold the bitcasts.
15605 DCI.AddToWorklist(V.getNode());
15606 }
15607 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
15608 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
15609 }
15610 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
15611 // Make the DAGCombiner fold the bitcasts.
15612 DCI.AddToWorklist(Vec.getNode());
15613 return Vec;
15614}
15615
15616static SDValue
15618 EVT VT = N->getValueType(0);
15619 SDValue Op = N->getOperand(0);
15620 SDLoc dl(N);
15621
15622 // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x)
15623 if (Op->getOpcode() == ARMISD::PREDICATE_CAST) {
15624 // If the valuetypes are the same, we can remove the cast entirely.
15625 if (Op->getOperand(0).getValueType() == VT)
15626 return Op->getOperand(0);
15627 return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
15628 }
15629
15630 // Turn pred_cast(xor x, -1) into xor(pred_cast x, -1), in order to produce
15631 // more VPNOT which might get folded as else predicates.
15632 if (Op.getValueType() == MVT::i32 && isBitwiseNot(Op)) {
15633 SDValue X =
15634 DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
15635 SDValue C = DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
15636 DCI.DAG.getConstant(65535, dl, MVT::i32));
15637 return DCI.DAG.getNode(ISD::XOR, dl, VT, X, C);
15638 }
15639
15640 // Only the bottom 16 bits of the source register are used.
15641 if (Op.getValueType() == MVT::i32) {
15642 APInt DemandedMask = APInt::getLowBitsSet(32, 16);
15644 if (TLI.SimplifyDemandedBits(Op, DemandedMask, DCI))
15645 return SDValue(N, 0);
15646 }
15647 return SDValue();
15648}
15649
15651 const ARMSubtarget *ST) {
15652 EVT VT = N->getValueType(0);
15653 SDValue Op = N->getOperand(0);
15654 SDLoc dl(N);
15655
15656 // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST
15657 if (ST->isLittle())
15658 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
15659
15660 // VT VECTOR_REG_CAST (VT Op) -> Op
15661 if (Op.getValueType() == VT)
15662 return Op;
15663 // VECTOR_REG_CAST undef -> undef
15664 if (Op.isUndef())
15665 return DAG.getUNDEF(VT);
15666
15667 // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x)
15668 if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) {
15669 // If the valuetypes are the same, we can remove the cast entirely.
15670 if (Op->getOperand(0).getValueType() == VT)
15671 return Op->getOperand(0);
15672 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Op->getOperand(0));
15673 }
15674
15675 return SDValue();
15676}
15677
15679 const ARMSubtarget *Subtarget) {
15680 if (!Subtarget->hasMVEIntegerOps())
15681 return SDValue();
15682
15683 EVT VT = N->getValueType(0);
15684 SDValue Op0 = N->getOperand(0);
15685 SDValue Op1 = N->getOperand(1);
15686 ARMCC::CondCodes Cond = (ARMCC::CondCodes)N->getConstantOperandVal(2);
15687 SDLoc dl(N);
15688
15689 // vcmp X, 0, cc -> vcmpz X, cc
15690 if (isZeroVector(Op1))
15691 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0, N->getOperand(2));
15692
15693 unsigned SwappedCond = getSwappedCondition(Cond);
15694 if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) {
15695 // vcmp 0, X, cc -> vcmpz X, reversed(cc)
15696 if (isZeroVector(Op0))
15697 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1,
15698 DAG.getConstant(SwappedCond, dl, MVT::i32));
15699 // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc)
15700 if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP)
15701 return DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0,
15702 DAG.getConstant(SwappedCond, dl, MVT::i32));
15703 }
15704
15705 return SDValue();
15706}
15707
15708/// PerformInsertEltCombine - Target-specific dag combine xforms for
15709/// ISD::INSERT_VECTOR_ELT.
15712 // Bitcast an i64 load inserted into a vector to f64.
15713 // Otherwise, the i64 value will be legalized to a pair of i32 values.
15714 EVT VT = N->getValueType(0);
15715 SDNode *Elt = N->getOperand(1).getNode();
15716 if (VT.getVectorElementType() != MVT::i64 ||
15717 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
15718 return SDValue();
15719
15720 SelectionDAG &DAG = DCI.DAG;
15721 SDLoc dl(N);
15722 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
15724 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
15725 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
15726 // Make the DAGCombiner fold the bitcasts.
15727 DCI.AddToWorklist(Vec.getNode());
15728 DCI.AddToWorklist(V.getNode());
15729 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
15730 Vec, V, N->getOperand(2));
15731 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
15732}
15733
15734// Convert a pair of extracts from the same base vector to a VMOVRRD. Either
15735// directly or bitcast to an integer if the original is a float vector.
15736// extract(x, n); extract(x, n+1) -> VMOVRRD(extract v2f64 x, n/2)
15737// bitcast(extract(x, n)); bitcast(extract(x, n+1)) -> VMOVRRD(extract x, n/2)
15738static SDValue
15740 EVT VT = N->getValueType(0);
15741 SDLoc dl(N);
15742
15743 if (!DCI.isAfterLegalizeDAG() || VT != MVT::i32 ||
15744 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(MVT::f64))
15745 return SDValue();
15746
15747 SDValue Ext = SDValue(N, 0);
15748 if (Ext.getOpcode() == ISD::BITCAST &&
15749 Ext.getOperand(0).getValueType() == MVT::f32)
15750 Ext = Ext.getOperand(0);
15751 if (Ext.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
15753 Ext.getConstantOperandVal(1) % 2 != 0)
15754 return SDValue();
15755 if (Ext->hasOneUse() && (Ext->user_begin()->getOpcode() == ISD::SINT_TO_FP ||
15756 Ext->user_begin()->getOpcode() == ISD::UINT_TO_FP))
15757 return SDValue();
15758
15759 SDValue Op0 = Ext.getOperand(0);
15760 EVT VecVT = Op0.getValueType();
15761 unsigned ResNo = Op0.getResNo();
15762 unsigned Lane = Ext.getConstantOperandVal(1);
15763 if (VecVT.getVectorNumElements() != 4)
15764 return SDValue();
15765
15766 // Find another extract, of Lane + 1
15767 auto OtherIt = find_if(Op0->users(), [&](SDNode *V) {
15768 return V->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15769 isa<ConstantSDNode>(V->getOperand(1)) &&
15770 V->getConstantOperandVal(1) == Lane + 1 &&
15771 V->getOperand(0).getResNo() == ResNo;
15772 });
15773 if (OtherIt == Op0->users().end())
15774 return SDValue();
15775
15776 // For float extracts, we need to be converting to a i32 for both vector
15777 // lanes.
15778 SDValue OtherExt(*OtherIt, 0);
15779 if (OtherExt.getValueType() != MVT::i32) {
15780 if (!OtherExt->hasOneUse() ||
15781 OtherExt->user_begin()->getOpcode() != ISD::BITCAST ||
15782 OtherExt->user_begin()->getValueType(0) != MVT::i32)
15783 return SDValue();
15784 OtherExt = SDValue(*OtherExt->user_begin(), 0);
15785 }
15786
15787 // Convert the type to a f64 and extract with a VMOVRRD.
15788 SDValue F64 = DCI.DAG.getNode(
15789 ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
15790 DCI.DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v2f64, Op0),
15791 DCI.DAG.getConstant(Ext.getConstantOperandVal(1) / 2, dl, MVT::i32));
15792 SDValue VMOVRRD =
15793 DCI.DAG.getNode(ARMISD::VMOVRRD, dl, {MVT::i32, MVT::i32}, F64);
15794
15795 DCI.CombineTo(OtherExt.getNode(), SDValue(VMOVRRD.getNode(), 1));
15796 return VMOVRRD;
15797}
15798
15801 const ARMSubtarget *ST) {
15802 SDValue Op0 = N->getOperand(0);
15803 EVT VT = N->getValueType(0);
15804 SDLoc dl(N);
15805
15806 // extract (vdup x) -> x
15807 if (Op0->getOpcode() == ARMISD::VDUP) {
15808 SDValue X = Op0->getOperand(0);
15809 if (VT == MVT::f16 && X.getValueType() == MVT::i32)
15810 return DCI.DAG.getNode(ARMISD::VMOVhr, dl, VT, X);
15811 if (VT == MVT::i32 && X.getValueType() == MVT::f16)
15812 return DCI.DAG.getNode(ARMISD::VMOVrh, dl, VT, X);
15813 if (VT == MVT::f32 && X.getValueType() == MVT::i32)
15814 return DCI.DAG.getNode(ISD::BITCAST, dl, VT, X);
15815
15816 while (X.getValueType() != VT && X->getOpcode() == ISD::BITCAST)
15817 X = X->getOperand(0);
15818 if (X.getValueType() == VT)
15819 return X;
15820 }
15821
15822 // extract ARM_BUILD_VECTOR -> x
15823 if (Op0->getOpcode() == ARMISD::BUILD_VECTOR &&
15824 isa<ConstantSDNode>(N->getOperand(1)) &&
15825 N->getConstantOperandVal(1) < Op0.getNumOperands()) {
15826 return Op0.getOperand(N->getConstantOperandVal(1));
15827 }
15828
15829 // extract(bitcast(BUILD_VECTOR(VMOVDRR(a, b), ..))) -> a or b
15830 if (Op0.getValueType() == MVT::v4i32 &&
15831 isa<ConstantSDNode>(N->getOperand(1)) &&
15832 Op0.getOpcode() == ISD::BITCAST &&
15834 Op0.getOperand(0).getValueType() == MVT::v2f64) {
15835 SDValue BV = Op0.getOperand(0);
15836 unsigned Offset = N->getConstantOperandVal(1);
15837 SDValue MOV = BV.getOperand(Offset < 2 ? 0 : 1);
15838 if (MOV.getOpcode() == ARMISD::VMOVDRR)
15839 return MOV.getOperand(ST->isLittle() ? Offset % 2 : 1 - Offset % 2);
15840 }
15841
15842 // extract x, n; extract x, n+1 -> VMOVRRD x
15843 if (SDValue R = PerformExtractEltToVMOVRRD(N, DCI))
15844 return R;
15845
15846 // extract (MVETrunc(x)) -> extract x
15847 if (Op0->getOpcode() == ARMISD::MVETRUNC) {
15848 unsigned Idx = N->getConstantOperandVal(1);
15849 unsigned Vec =
15851 unsigned SubIdx =
15853 return DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Op0.getOperand(Vec),
15854 DCI.DAG.getConstant(SubIdx, dl, MVT::i32));
15855 }
15856
15857 // extract(bitcast(BUILD_VECTOR(extract(bitcast(a)), ..))) -> extract(a)
15858 if (ST->isLittle() && Op0.getOpcode() == ISD::BITCAST &&
15860 isa<ConstantSDNode>(N->getOperand(1)) &&
15863 unsigned Lane = N->getConstantOperandVal(1);
15864 EVT ExtVT = Op0.getValueType();
15865 EVT BVVT = Op0.getOperand(0).getValueType();
15866 unsigned BVLane =
15867 (Lane * BVVT.getVectorNumElements()) / ExtVT.getVectorNumElements();
15868 assert(BVLane < Op0.getOperand(0).getNumOperands());
15869 SDValue Ext = Op0.getOperand(0).getOperand(BVLane);
15870 if (Ext.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15871 Ext.getOperand(0).getOpcode() == ISD::BITCAST &&
15873 Ext.getOperand(0).getOperand(0).getValueType() == ExtVT) {
15874 unsigned InnerLane = Ext.getConstantOperandVal(1);
15875 unsigned BVSubLane = Lane - (BVLane * ExtVT.getVectorNumElements()) /
15876 BVVT.getVectorNumElements();
15877 unsigned FinalLane = (InnerLane * ExtVT.getVectorNumElements()) /
15878 BVVT.getVectorNumElements() +
15879 BVSubLane;
15880 return DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT,
15881 Ext.getOperand(0).getOperand(0),
15882 DCI.DAG.getConstant(FinalLane, dl, MVT::i32));
15883 }
15884 }
15885
15886 return SDValue();
15887}
15888
15890 SDValue Op = N->getOperand(0);
15891 EVT VT = N->getValueType(0);
15892
15893 // sext_inreg(VGETLANEu) -> VGETLANEs
15894 if (Op.getOpcode() == ARMISD::VGETLANEu &&
15895 cast<VTSDNode>(N->getOperand(1))->getVT() ==
15896 Op.getOperand(0).getValueType().getScalarType())
15897 return DAG.getNode(ARMISD::VGETLANEs, SDLoc(N), VT, Op.getOperand(0),
15898 Op.getOperand(1));
15899
15900 return SDValue();
15901}
15902
15903static SDValue
15905 SDValue Vec = N->getOperand(0);
15906 SDValue SubVec = N->getOperand(1);
15907 uint64_t IdxVal = N->getConstantOperandVal(2);
15908 EVT VecVT = Vec.getValueType();
15909 EVT SubVT = SubVec.getValueType();
15910
15911 // Only do this for legal fixed vector types.
15912 if (!VecVT.isFixedLengthVector() ||
15913 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(VecVT) ||
15915 return SDValue();
15916
15917 // Ignore widening patterns.
15918 if (IdxVal == 0 && Vec.isUndef())
15919 return SDValue();
15920
15921 // Subvector must be half the width and an "aligned" insertion.
15922 unsigned NumSubElts = SubVT.getVectorNumElements();
15923 if ((SubVT.getSizeInBits() * 2) != VecVT.getSizeInBits() ||
15924 (IdxVal != 0 && IdxVal != NumSubElts))
15925 return SDValue();
15926
15927 // Fold insert_subvector -> concat_vectors
15928 // insert_subvector(Vec,Sub,lo) -> concat_vectors(Sub,extract(Vec,hi))
15929 // insert_subvector(Vec,Sub,hi) -> concat_vectors(extract(Vec,lo),Sub)
15930 SDLoc DL(N);
15931 SDValue Lo, Hi;
15932 if (IdxVal == 0) {
15933 Lo = SubVec;
15934 Hi = DCI.DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
15935 DCI.DAG.getVectorIdxConstant(NumSubElts, DL));
15936 } else {
15937 Lo = DCI.DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
15938 DCI.DAG.getVectorIdxConstant(0, DL));
15939 Hi = SubVec;
15940 }
15941 return DCI.DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Lo, Hi);
15942}
15943
15944// shuffle(MVETrunc(x, y)) -> VMOVN(x, y)
15946 SelectionDAG &DAG) {
15947 SDValue Trunc = N->getOperand(0);
15948 EVT VT = Trunc.getValueType();
15949 if (Trunc.getOpcode() != ARMISD::MVETRUNC || !N->getOperand(1).isUndef())
15950 return SDValue();
15951
15952 SDLoc DL(Trunc);
15953 if (isVMOVNTruncMask(N->getMask(), VT, false))
15954 return DAG.getNode(
15955 ARMISD::VMOVN, DL, VT,
15956 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(0)),
15957 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(1)),
15958 DAG.getConstant(1, DL, MVT::i32));
15959 else if (isVMOVNTruncMask(N->getMask(), VT, true))
15960 return DAG.getNode(
15961 ARMISD::VMOVN, DL, VT,
15962 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(1)),
15963 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(0)),
15964 DAG.getConstant(1, DL, MVT::i32));
15965 return SDValue();
15966}
15967
15968/// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
15969/// ISD::VECTOR_SHUFFLE.
15972 return R;
15973
15974 // The LLVM shufflevector instruction does not require the shuffle mask
15975 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
15976 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
15977 // operands do not match the mask length, they are extended by concatenating
15978 // them with undef vectors. That is probably the right thing for other
15979 // targets, but for NEON it is better to concatenate two double-register
15980 // size vector operands into a single quad-register size vector. Do that
15981 // transformation here:
15982 // shuffle(concat(v1, undef), concat(v2, undef)) ->
15983 // shuffle(concat(v1, v2), undef)
15984 SDValue Op0 = N->getOperand(0);
15985 SDValue Op1 = N->getOperand(1);
15986 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
15987 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
15988 Op0.getNumOperands() != 2 ||
15989 Op1.getNumOperands() != 2)
15990 return SDValue();
15991 SDValue Concat0Op1 = Op0.getOperand(1);
15992 SDValue Concat1Op1 = Op1.getOperand(1);
15993 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
15994 return SDValue();
15995 // Skip the transformation if any of the types are illegal.
15997 EVT VT = N->getValueType(0);
15998 if (!TLI.isTypeLegal(VT) ||
15999 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
16000 !TLI.isTypeLegal(Concat1Op1.getValueType()))
16001 return SDValue();
16002
16003 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
16004 Op0.getOperand(0), Op1.getOperand(0));
16005 // Translate the shuffle mask.
16006 SmallVector<int, 16> NewMask;
16007 unsigned NumElts = VT.getVectorNumElements();
16008 unsigned HalfElts = NumElts/2;
16010 for (unsigned n = 0; n < NumElts; ++n) {
16011 int MaskElt = SVN->getMaskElt(n);
16012 int NewElt = -1;
16013 if (MaskElt < (int)HalfElts)
16014 NewElt = MaskElt;
16015 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
16016 NewElt = HalfElts + MaskElt - NumElts;
16017 NewMask.push_back(NewElt);
16018 }
16019 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
16020 DAG.getUNDEF(VT), NewMask);
16021}
16022
16023/// Load/store instruction that can be merged with a base address
16024/// update
16029 unsigned AddrOpIdx;
16030};
16031
16033 /// Instruction that updates a pointer
16035 /// Pointer increment operand
16037 /// Pointer increment value if it is a constant, or 0 otherwise
16038 unsigned ConstInc;
16039};
16040
16042 // Check that the add is independent of the load/store.
16043 // Otherwise, folding it would create a cycle. Search through Addr
16044 // as well, since the User may not be a direct user of Addr and
16045 // only share a base pointer.
16048 Worklist.push_back(N);
16049 Worklist.push_back(User);
16050 const unsigned MaxSteps = 1024;
16051 if (SDNode::hasPredecessorHelper(N, Visited, Worklist, MaxSteps) ||
16052 SDNode::hasPredecessorHelper(User, Visited, Worklist, MaxSteps))
16053 return false;
16054 return true;
16055}
16056
16058 struct BaseUpdateUser &User,
16059 bool SimpleConstIncOnly,
16061 SelectionDAG &DAG = DCI.DAG;
16062 SDNode *N = Target.N;
16064 SDLoc dl(N);
16065
16066 // Find the new opcode for the updating load/store.
16067 bool isLoadOp = true;
16068 bool isLaneOp = false;
16069 // Workaround for vst1x and vld1x intrinsics which do not have alignment
16070 // as an operand.
16071 bool hasAlignment = true;
16072 unsigned NewOpc = 0;
16073 unsigned NumVecs = 0;
16074 if (Target.isIntrinsic) {
16075 unsigned IntNo = N->getConstantOperandVal(1);
16076 switch (IntNo) {
16077 default:
16078 llvm_unreachable("unexpected intrinsic for Neon base update");
16079 case Intrinsic::arm_neon_vld1:
16080 NewOpc = ARMISD::VLD1_UPD;
16081 NumVecs = 1;
16082 break;
16083 case Intrinsic::arm_neon_vld2:
16084 NewOpc = ARMISD::VLD2_UPD;
16085 NumVecs = 2;
16086 break;
16087 case Intrinsic::arm_neon_vld3:
16088 NewOpc = ARMISD::VLD3_UPD;
16089 NumVecs = 3;
16090 break;
16091 case Intrinsic::arm_neon_vld4:
16092 NewOpc = ARMISD::VLD4_UPD;
16093 NumVecs = 4;
16094 break;
16095 case Intrinsic::arm_neon_vld1x2:
16096 NewOpc = ARMISD::VLD1x2_UPD;
16097 NumVecs = 2;
16098 hasAlignment = false;
16099 break;
16100 case Intrinsic::arm_neon_vld1x3:
16101 NewOpc = ARMISD::VLD1x3_UPD;
16102 NumVecs = 3;
16103 hasAlignment = false;
16104 break;
16105 case Intrinsic::arm_neon_vld1x4:
16106 NewOpc = ARMISD::VLD1x4_UPD;
16107 NumVecs = 4;
16108 hasAlignment = false;
16109 break;
16110 case Intrinsic::arm_neon_vld2dup:
16111 NewOpc = ARMISD::VLD2DUP_UPD;
16112 NumVecs = 2;
16113 break;
16114 case Intrinsic::arm_neon_vld3dup:
16115 NewOpc = ARMISD::VLD3DUP_UPD;
16116 NumVecs = 3;
16117 break;
16118 case Intrinsic::arm_neon_vld4dup:
16119 NewOpc = ARMISD::VLD4DUP_UPD;
16120 NumVecs = 4;
16121 break;
16122 case Intrinsic::arm_neon_vld2lane:
16123 NewOpc = ARMISD::VLD2LN_UPD;
16124 NumVecs = 2;
16125 isLaneOp = true;
16126 break;
16127 case Intrinsic::arm_neon_vld3lane:
16128 NewOpc = ARMISD::VLD3LN_UPD;
16129 NumVecs = 3;
16130 isLaneOp = true;
16131 break;
16132 case Intrinsic::arm_neon_vld4lane:
16133 NewOpc = ARMISD::VLD4LN_UPD;
16134 NumVecs = 4;
16135 isLaneOp = true;
16136 break;
16137 case Intrinsic::arm_neon_vst1:
16138 NewOpc = ARMISD::VST1_UPD;
16139 NumVecs = 1;
16140 isLoadOp = false;
16141 break;
16142 case Intrinsic::arm_neon_vst2:
16143 NewOpc = ARMISD::VST2_UPD;
16144 NumVecs = 2;
16145 isLoadOp = false;
16146 break;
16147 case Intrinsic::arm_neon_vst3:
16148 NewOpc = ARMISD::VST3_UPD;
16149 NumVecs = 3;
16150 isLoadOp = false;
16151 break;
16152 case Intrinsic::arm_neon_vst4:
16153 NewOpc = ARMISD::VST4_UPD;
16154 NumVecs = 4;
16155 isLoadOp = false;
16156 break;
16157 case Intrinsic::arm_neon_vst2lane:
16158 NewOpc = ARMISD::VST2LN_UPD;
16159 NumVecs = 2;
16160 isLoadOp = false;
16161 isLaneOp = true;
16162 break;
16163 case Intrinsic::arm_neon_vst3lane:
16164 NewOpc = ARMISD::VST3LN_UPD;
16165 NumVecs = 3;
16166 isLoadOp = false;
16167 isLaneOp = true;
16168 break;
16169 case Intrinsic::arm_neon_vst4lane:
16170 NewOpc = ARMISD::VST4LN_UPD;
16171 NumVecs = 4;
16172 isLoadOp = false;
16173 isLaneOp = true;
16174 break;
16175 case Intrinsic::arm_neon_vst1x2:
16176 NewOpc = ARMISD::VST1x2_UPD;
16177 NumVecs = 2;
16178 isLoadOp = false;
16179 hasAlignment = false;
16180 break;
16181 case Intrinsic::arm_neon_vst1x3:
16182 NewOpc = ARMISD::VST1x3_UPD;
16183 NumVecs = 3;
16184 isLoadOp = false;
16185 hasAlignment = false;
16186 break;
16187 case Intrinsic::arm_neon_vst1x4:
16188 NewOpc = ARMISD::VST1x4_UPD;
16189 NumVecs = 4;
16190 isLoadOp = false;
16191 hasAlignment = false;
16192 break;
16193 }
16194 } else {
16195 isLaneOp = true;
16196 switch (N->getOpcode()) {
16197 default:
16198 llvm_unreachable("unexpected opcode for Neon base update");
16199 case ARMISD::VLD1DUP:
16200 NewOpc = ARMISD::VLD1DUP_UPD;
16201 NumVecs = 1;
16202 break;
16203 case ARMISD::VLD2DUP:
16204 NewOpc = ARMISD::VLD2DUP_UPD;
16205 NumVecs = 2;
16206 break;
16207 case ARMISD::VLD3DUP:
16208 NewOpc = ARMISD::VLD3DUP_UPD;
16209 NumVecs = 3;
16210 break;
16211 case ARMISD::VLD4DUP:
16212 NewOpc = ARMISD::VLD4DUP_UPD;
16213 NumVecs = 4;
16214 break;
16215 case ISD::LOAD:
16216 NewOpc = ARMISD::VLD1_UPD;
16217 NumVecs = 1;
16218 isLaneOp = false;
16219 break;
16220 case ISD::STORE:
16221 NewOpc = ARMISD::VST1_UPD;
16222 NumVecs = 1;
16223 isLaneOp = false;
16224 isLoadOp = false;
16225 break;
16226 }
16227 }
16228
16229 // Find the size of memory referenced by the load/store.
16230 EVT VecTy;
16231 if (isLoadOp) {
16232 VecTy = N->getValueType(0);
16233 } else if (Target.isIntrinsic) {
16234 VecTy = N->getOperand(Target.AddrOpIdx + 1).getValueType();
16235 } else {
16236 assert(Target.isStore &&
16237 "Node has to be a load, a store, or an intrinsic!");
16238 VecTy = N->getOperand(1).getValueType();
16239 }
16240
16241 bool isVLDDUPOp =
16242 NewOpc == ARMISD::VLD1DUP_UPD || NewOpc == ARMISD::VLD2DUP_UPD ||
16243 NewOpc == ARMISD::VLD3DUP_UPD || NewOpc == ARMISD::VLD4DUP_UPD;
16244
16245 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
16246 if (isLaneOp || isVLDDUPOp)
16247 NumBytes /= VecTy.getVectorNumElements();
16248
16249 if (NumBytes >= 3 * 16 && User.ConstInc != NumBytes) {
16250 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
16251 // separate instructions that make it harder to use a non-constant update.
16252 return false;
16253 }
16254
16255 if (SimpleConstIncOnly && User.ConstInc != NumBytes)
16256 return false;
16257
16258 if (!isValidBaseUpdate(N, User.N))
16259 return false;
16260
16261 // OK, we found an ADD we can fold into the base update.
16262 // Now, create a _UPD node, taking care of not breaking alignment.
16263
16264 EVT AlignedVecTy = VecTy;
16265 Align Alignment = MemN->getAlign();
16266
16267 // If this is a less-than-standard-aligned load/store, change the type to
16268 // match the standard alignment.
16269 // The alignment is overlooked when selecting _UPD variants; and it's
16270 // easier to introduce bitcasts here than fix that.
16271 // There are 3 ways to get to this base-update combine:
16272 // - intrinsics: they are assumed to be properly aligned (to the standard
16273 // alignment of the memory type), so we don't need to do anything.
16274 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
16275 // intrinsics, so, likewise, there's nothing to do.
16276 // - generic load/store instructions: the alignment is specified as an
16277 // explicit operand, rather than implicitly as the standard alignment
16278 // of the memory type (like the intrinsics). We need to change the
16279 // memory type to match the explicit alignment. That way, we don't
16280 // generate non-standard-aligned ARMISD::VLDx nodes.
16281 if (isa<LSBaseSDNode>(N)) {
16282 if (Alignment.value() < VecTy.getScalarSizeInBits() / 8) {
16283 MVT EltTy = MVT::getIntegerVT(Alignment.value() * 8);
16284 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
16285 assert(!isLaneOp && "Unexpected generic load/store lane.");
16286 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
16287 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
16288 }
16289 // Don't set an explicit alignment on regular load/stores that we want
16290 // to transform to VLD/VST 1_UPD nodes.
16291 // This matches the behavior of regular load/stores, which only get an
16292 // explicit alignment if the MMO alignment is larger than the standard
16293 // alignment of the memory type.
16294 // Intrinsics, however, always get an explicit alignment, set to the
16295 // alignment of the MMO.
16296 Alignment = Align(1);
16297 }
16298
16299 // Create the new updating load/store node.
16300 // First, create an SDVTList for the new updating node's results.
16301 EVT Tys[6];
16302 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
16303 unsigned n;
16304 for (n = 0; n < NumResultVecs; ++n)
16305 Tys[n] = AlignedVecTy;
16306 Tys[n++] = MVT::i32;
16307 Tys[n] = MVT::Other;
16308 SDVTList SDTys = DAG.getVTList(ArrayRef(Tys, NumResultVecs + 2));
16309
16310 // Then, gather the new node's operands.
16312 Ops.push_back(N->getOperand(0)); // incoming chain
16313 Ops.push_back(N->getOperand(Target.AddrOpIdx));
16314 Ops.push_back(User.Inc);
16315
16316 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
16317 // Try to match the intrinsic's signature
16318 Ops.push_back(StN->getValue());
16319 } else {
16320 // Loads (and of course intrinsics) match the intrinsics' signature,
16321 // so just add all but the alignment operand.
16322 unsigned LastOperand =
16323 hasAlignment ? N->getNumOperands() - 1 : N->getNumOperands();
16324 for (unsigned i = Target.AddrOpIdx + 1; i < LastOperand; ++i)
16325 Ops.push_back(N->getOperand(i));
16326 }
16327
16328 // For all node types, the alignment operand is always the last one.
16329 Ops.push_back(DAG.getConstant(Alignment.value(), dl, MVT::i32));
16330
16331 // If this is a non-standard-aligned STORE, the penultimate operand is the
16332 // stored value. Bitcast it to the aligned type.
16333 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
16334 SDValue &StVal = Ops[Ops.size() - 2];
16335 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
16336 }
16337
16338 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
16339 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
16340 MemN->getMemOperand());
16341
16342 // Update the uses.
16343 SmallVector<SDValue, 5> NewResults;
16344 for (unsigned i = 0; i < NumResultVecs; ++i)
16345 NewResults.push_back(SDValue(UpdN.getNode(), i));
16346
16347 // If this is an non-standard-aligned LOAD, the first result is the loaded
16348 // value. Bitcast it to the expected result type.
16349 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
16350 SDValue &LdVal = NewResults[0];
16351 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
16352 }
16353
16354 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
16355 DCI.CombineTo(N, NewResults);
16356 DCI.CombineTo(User.N, SDValue(UpdN.getNode(), NumResultVecs));
16357
16358 return true;
16359}
16360
16361// If (opcode ptr inc) is and ADD-like instruction, return the
16362// increment value. Otherwise return 0.
16363static unsigned getPointerConstIncrement(unsigned Opcode, SDValue Ptr,
16364 SDValue Inc, const SelectionDAG &DAG) {
16366 if (!CInc)
16367 return 0;
16368
16369 switch (Opcode) {
16370 case ARMISD::VLD1_UPD:
16371 case ISD::ADD:
16372 return CInc->getZExtValue();
16373 case ISD::OR: {
16374 if (DAG.haveNoCommonBitsSet(Ptr, Inc)) {
16375 // (OR ptr inc) is the same as (ADD ptr inc)
16376 return CInc->getZExtValue();
16377 }
16378 return 0;
16379 }
16380 default:
16381 return 0;
16382 }
16383}
16384
16386 switch (N->getOpcode()) {
16387 case ISD::ADD:
16388 case ISD::OR: {
16389 if (isa<ConstantSDNode>(N->getOperand(1))) {
16390 *Ptr = N->getOperand(0);
16391 *CInc = N->getOperand(1);
16392 return true;
16393 }
16394 return false;
16395 }
16396 case ARMISD::VLD1_UPD: {
16397 if (isa<ConstantSDNode>(N->getOperand(2))) {
16398 *Ptr = N->getOperand(1);
16399 *CInc = N->getOperand(2);
16400 return true;
16401 }
16402 return false;
16403 }
16404 default:
16405 return false;
16406 }
16407}
16408
16409/// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
16410/// NEON load/store intrinsics, and generic vector load/stores, to merge
16411/// base address updates.
16412/// For generic load/stores, the memory type is assumed to be a vector.
16413/// The caller is assumed to have checked legality.
16416 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
16417 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
16418 const bool isStore = N->getOpcode() == ISD::STORE;
16419 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
16420 BaseUpdateTarget Target = {N, isIntrinsic, isStore, AddrOpIdx};
16421
16422 // Limit the number of possible base-updates we look at to prevent degenerate
16423 // cases.
16424 unsigned MaxBaseUpdates = ArmMaxBaseUpdatesToCheck;
16425
16426 SDValue Addr = N->getOperand(AddrOpIdx);
16427
16429
16430 // Search for a use of the address operand that is an increment.
16431 for (SDUse &Use : Addr->uses()) {
16432 SDNode *User = Use.getUser();
16433 if (Use.getResNo() != Addr.getResNo() || User->getNumOperands() != 2)
16434 continue;
16435
16436 SDValue Inc = User->getOperand(Use.getOperandNo() == 1 ? 0 : 1);
16437 unsigned ConstInc =
16438 getPointerConstIncrement(User->getOpcode(), Addr, Inc, DCI.DAG);
16439
16440 if (ConstInc || User->getOpcode() == ISD::ADD) {
16441 BaseUpdates.push_back({User, Inc, ConstInc});
16442 if (BaseUpdates.size() >= MaxBaseUpdates)
16443 break;
16444 }
16445 }
16446
16447 // If the address is a constant pointer increment itself, find
16448 // another constant increment that has the same base operand
16449 SDValue Base;
16450 SDValue CInc;
16451 if (findPointerConstIncrement(Addr.getNode(), &Base, &CInc)) {
16452 unsigned Offset =
16453 getPointerConstIncrement(Addr->getOpcode(), Base, CInc, DCI.DAG);
16454 if (Offset) {
16455 for (SDUse &Use : Base->uses()) {
16456
16457 SDNode *User = Use.getUser();
16458 if (Use.getResNo() != Base.getResNo() || User == Addr.getNode() ||
16459 User->getNumOperands() != 2)
16460 continue;
16461
16462 SDValue UserInc = User->getOperand(Use.getOperandNo() == 0 ? 1 : 0);
16463 unsigned UserOffset =
16464 getPointerConstIncrement(User->getOpcode(), Base, UserInc, DCI.DAG);
16465
16466 if (!UserOffset || UserOffset <= Offset)
16467 continue;
16468
16469 unsigned NewConstInc = UserOffset - Offset;
16470 SDValue NewInc = DCI.DAG.getConstant(NewConstInc, SDLoc(N), MVT::i32);
16471 BaseUpdates.push_back({User, NewInc, NewConstInc});
16472 if (BaseUpdates.size() >= MaxBaseUpdates)
16473 break;
16474 }
16475 }
16476 }
16477
16478 // Try to fold the load/store with an update that matches memory
16479 // access size. This should work well for sequential loads.
16480 unsigned NumValidUpd = BaseUpdates.size();
16481 for (unsigned I = 0; I < NumValidUpd; I++) {
16482 BaseUpdateUser &User = BaseUpdates[I];
16483 if (TryCombineBaseUpdate(Target, User, /*SimpleConstIncOnly=*/true, DCI))
16484 return SDValue();
16485 }
16486
16487 // Try to fold with other users. Non-constant updates are considered
16488 // first, and constant updates are sorted to not break a sequence of
16489 // strided accesses (if there is any).
16490 llvm::stable_sort(BaseUpdates,
16491 [](const BaseUpdateUser &LHS, const BaseUpdateUser &RHS) {
16492 return LHS.ConstInc < RHS.ConstInc;
16493 });
16494 for (BaseUpdateUser &User : BaseUpdates) {
16495 if (TryCombineBaseUpdate(Target, User, /*SimpleConstIncOnly=*/false, DCI))
16496 return SDValue();
16497 }
16498 return SDValue();
16499}
16500
16503 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16504 return SDValue();
16505
16506 return CombineBaseUpdate(N, DCI);
16507}
16508
16511 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16512 return SDValue();
16513
16514 SelectionDAG &DAG = DCI.DAG;
16515 SDValue Addr = N->getOperand(2);
16517 SDLoc dl(N);
16518
16519 // For the stores, where there are multiple intrinsics we only actually want
16520 // to post-inc the last of the them.
16521 unsigned IntNo = N->getConstantOperandVal(1);
16522 if (IntNo == Intrinsic::arm_mve_vst2q && N->getConstantOperandVal(5) != 1)
16523 return SDValue();
16524 if (IntNo == Intrinsic::arm_mve_vst4q && N->getConstantOperandVal(7) != 3)
16525 return SDValue();
16526
16527 // Search for a use of the address operand that is an increment.
16528 for (SDUse &Use : Addr->uses()) {
16529 SDNode *User = Use.getUser();
16530 if (User->getOpcode() != ISD::ADD || Use.getResNo() != Addr.getResNo())
16531 continue;
16532
16533 // Check that the add is independent of the load/store. Otherwise, folding
16534 // it would create a cycle. We can avoid searching through Addr as it's a
16535 // predecessor to both.
16538 Visited.insert(Addr.getNode());
16539 Worklist.push_back(N);
16540 Worklist.push_back(User);
16541 const unsigned MaxSteps = 1024;
16542 if (SDNode::hasPredecessorHelper(N, Visited, Worklist, MaxSteps) ||
16543 SDNode::hasPredecessorHelper(User, Visited, Worklist, MaxSteps))
16544 continue;
16545
16546 // Find the new opcode for the updating load/store.
16547 bool isLoadOp = true;
16548 unsigned NewOpc = 0;
16549 unsigned NumVecs = 0;
16550 switch (IntNo) {
16551 default:
16552 llvm_unreachable("unexpected intrinsic for MVE VLDn combine");
16553 case Intrinsic::arm_mve_vld2q:
16554 NewOpc = ARMISD::VLD2_UPD;
16555 NumVecs = 2;
16556 break;
16557 case Intrinsic::arm_mve_vld4q:
16558 NewOpc = ARMISD::VLD4_UPD;
16559 NumVecs = 4;
16560 break;
16561 case Intrinsic::arm_mve_vst2q:
16562 NewOpc = ARMISD::VST2_UPD;
16563 NumVecs = 2;
16564 isLoadOp = false;
16565 break;
16566 case Intrinsic::arm_mve_vst4q:
16567 NewOpc = ARMISD::VST4_UPD;
16568 NumVecs = 4;
16569 isLoadOp = false;
16570 break;
16571 }
16572
16573 // Find the size of memory referenced by the load/store.
16574 EVT VecTy;
16575 if (isLoadOp) {
16576 VecTy = N->getValueType(0);
16577 } else {
16578 VecTy = N->getOperand(3).getValueType();
16579 }
16580
16581 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
16582
16583 // If the increment is a constant, it must match the memory ref size.
16584 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
16586 if (!CInc || CInc->getZExtValue() != NumBytes)
16587 continue;
16588
16589 // Create the new updating load/store node.
16590 // First, create an SDVTList for the new updating node's results.
16591 EVT Tys[6];
16592 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
16593 unsigned n;
16594 for (n = 0; n < NumResultVecs; ++n)
16595 Tys[n] = VecTy;
16596 Tys[n++] = MVT::i32;
16597 Tys[n] = MVT::Other;
16598 SDVTList SDTys = DAG.getVTList(ArrayRef(Tys, NumResultVecs + 2));
16599
16600 // Then, gather the new node's operands.
16602 Ops.push_back(N->getOperand(0)); // incoming chain
16603 Ops.push_back(N->getOperand(2)); // ptr
16604 Ops.push_back(Inc);
16605
16606 for (unsigned i = 3; i < N->getNumOperands(); ++i)
16607 Ops.push_back(N->getOperand(i));
16608
16609 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, VecTy,
16610 MemN->getMemOperand());
16611
16612 // Update the uses.
16613 SmallVector<SDValue, 5> NewResults;
16614 for (unsigned i = 0; i < NumResultVecs; ++i)
16615 NewResults.push_back(SDValue(UpdN.getNode(), i));
16616
16617 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
16618 DCI.CombineTo(N, NewResults);
16619 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
16620
16621 break;
16622 }
16623
16624 return SDValue();
16625}
16626
16627/// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
16628/// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
16629/// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
16630/// return true.
16632 SelectionDAG &DAG = DCI.DAG;
16633 EVT VT = N->getValueType(0);
16634 // vldN-dup instructions only support 64-bit vectors for N > 1.
16635 if (!VT.is64BitVector())
16636 return false;
16637
16638 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
16639 SDNode *VLD = N->getOperand(0).getNode();
16640 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
16641 return false;
16642 unsigned NumVecs = 0;
16643 unsigned NewOpc = 0;
16644 unsigned IntNo = VLD->getConstantOperandVal(1);
16645 if (IntNo == Intrinsic::arm_neon_vld2lane) {
16646 NumVecs = 2;
16647 NewOpc = ARMISD::VLD2DUP;
16648 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
16649 NumVecs = 3;
16650 NewOpc = ARMISD::VLD3DUP;
16651 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
16652 NumVecs = 4;
16653 NewOpc = ARMISD::VLD4DUP;
16654 } else {
16655 return false;
16656 }
16657
16658 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
16659 // numbers match the load.
16660 unsigned VLDLaneNo = VLD->getConstantOperandVal(NumVecs + 3);
16661 for (SDUse &Use : VLD->uses()) {
16662 // Ignore uses of the chain result.
16663 if (Use.getResNo() == NumVecs)
16664 continue;
16665 SDNode *User = Use.getUser();
16666 if (User->getOpcode() != ARMISD::VDUPLANE ||
16667 VLDLaneNo != User->getConstantOperandVal(1))
16668 return false;
16669 }
16670
16671 // Create the vldN-dup node.
16672 EVT Tys[5];
16673 unsigned n;
16674 for (n = 0; n < NumVecs; ++n)
16675 Tys[n] = VT;
16676 Tys[n] = MVT::Other;
16677 SDVTList SDTys = DAG.getVTList(ArrayRef(Tys, NumVecs + 1));
16678 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
16680 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
16681 Ops, VLDMemInt->getMemoryVT(),
16682 VLDMemInt->getMemOperand());
16683
16684 // Update the uses.
16685 for (SDUse &Use : VLD->uses()) {
16686 unsigned ResNo = Use.getResNo();
16687 // Ignore uses of the chain result.
16688 if (ResNo == NumVecs)
16689 continue;
16690 DCI.CombineTo(Use.getUser(), SDValue(VLDDup.getNode(), ResNo));
16691 }
16692
16693 // Now the vldN-lane intrinsic is dead except for its chain result.
16694 // Update uses of the chain.
16695 std::vector<SDValue> VLDDupResults;
16696 for (unsigned n = 0; n < NumVecs; ++n)
16697 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
16698 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
16699 DCI.CombineTo(VLD, VLDDupResults);
16700
16701 return true;
16702}
16703
16704/// PerformVDUPLANECombine - Target-specific dag combine xforms for
16705/// ARMISD::VDUPLANE.
16708 const ARMSubtarget *Subtarget) {
16709 SDValue Op = N->getOperand(0);
16710 EVT VT = N->getValueType(0);
16711
16712 // On MVE, we just convert the VDUPLANE to a VDUP with an extract.
16713 if (Subtarget->hasMVEIntegerOps()) {
16714 EVT ExtractVT = VT.getVectorElementType();
16715 // We need to ensure we are creating a legal type.
16716 if (!DCI.DAG.getTargetLoweringInfo().isTypeLegal(ExtractVT))
16717 ExtractVT = MVT::i32;
16718 SDValue Extract = DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), ExtractVT,
16719 N->getOperand(0), N->getOperand(1));
16720 return DCI.DAG.getNode(ARMISD::VDUP, SDLoc(N), VT, Extract);
16721 }
16722
16723 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
16724 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
16725 if (CombineVLDDUP(N, DCI))
16726 return SDValue(N, 0);
16727
16728 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
16729 // redundant. Ignore bit_converts for now; element sizes are checked below.
16730 while (Op.getOpcode() == ISD::BITCAST)
16731 Op = Op.getOperand(0);
16732 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
16733 return SDValue();
16734
16735 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
16736 unsigned EltSize = Op.getScalarValueSizeInBits();
16737 // The canonical VMOV for a zero vector uses a 32-bit element size.
16738 unsigned Imm = Op.getConstantOperandVal(0);
16739 unsigned EltBits;
16740 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
16741 EltSize = 8;
16742 if (EltSize > VT.getScalarSizeInBits())
16743 return SDValue();
16744
16745 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
16746}
16747
16748/// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
16750 const ARMSubtarget *Subtarget) {
16751 SDValue Op = N->getOperand(0);
16752 SDLoc dl(N);
16753
16754 if (Subtarget->hasMVEIntegerOps()) {
16755 // Convert VDUP f32 -> VDUP BITCAST i32 under MVE, as we know the value will
16756 // need to come from a GPR.
16757 if (Op.getValueType() == MVT::f32)
16758 return DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
16759 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op));
16760 else if (Op.getValueType() == MVT::f16)
16761 return DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
16762 DAG.getNode(ARMISD::VMOVrh, dl, MVT::i32, Op));
16763 }
16764
16765 if (!Subtarget->hasNEON())
16766 return SDValue();
16767
16768 // Match VDUP(LOAD) -> VLD1DUP.
16769 // We match this pattern here rather than waiting for isel because the
16770 // transform is only legal for unindexed loads.
16771 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
16772 if (LD && Op.hasOneUse() && LD->isUnindexed() &&
16773 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
16774 SDValue Ops[] = {LD->getOperand(0), LD->getOperand(1),
16775 DAG.getConstant(LD->getAlign().value(), SDLoc(N), MVT::i32)};
16776 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
16777 SDValue VLDDup =
16779 LD->getMemoryVT(), LD->getMemOperand());
16780 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
16781 return VLDDup;
16782 }
16783
16784 return SDValue();
16785}
16786
16789 const ARMSubtarget *Subtarget) {
16790 EVT VT = N->getValueType(0);
16791 // Let the deinterleave combine form a structured load first.
16793 for (SDUse &Use : N->uses())
16794 if (Use.getUser()->getOpcode() == ISD::VECTOR_DEINTERLEAVE)
16795 return SDValue();
16796 // If this is a legal vector load, try to combine it into a VLD1_UPD.
16797 if (Subtarget->hasNEON() && ISD::isNormalLoad(N) && VT.isVector() &&
16799 return CombineBaseUpdate(N, DCI);
16800
16801 return SDValue();
16802}
16803
16804// Optimize trunc store (of multiple scalars) to shuffle and store. First,
16805// pack all of the elements in one place. Next, store to memory in fewer
16806// chunks.
16808 SelectionDAG &DAG) {
16809 SDValue StVal = St->getValue();
16810 EVT VT = StVal.getValueType();
16811 if (!St->isTruncatingStore() || !VT.isVector())
16812 return SDValue();
16814 EVT StVT = St->getMemoryVT();
16815 unsigned NumElems = VT.getVectorNumElements();
16816 assert(StVT != VT && "Cannot truncate to the same type");
16817 unsigned FromEltSz = VT.getScalarSizeInBits();
16818 unsigned ToEltSz = StVT.getScalarSizeInBits();
16819
16820 // From, To sizes and ElemCount must be pow of two
16821 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz))
16822 return SDValue();
16823
16824 // We are going to use the original vector elt for storing.
16825 // Accumulated smaller vector elements must be a multiple of the store size.
16826 if (0 != (NumElems * FromEltSz) % ToEltSz)
16827 return SDValue();
16828
16829 unsigned SizeRatio = FromEltSz / ToEltSz;
16830 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
16831
16832 // Create a type on which we perform the shuffle.
16833 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
16834 NumElems * SizeRatio);
16835 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16836
16837 SDLoc DL(St);
16838 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
16839 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16840 for (unsigned i = 0; i < NumElems; ++i)
16841 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1
16842 : i * SizeRatio;
16843
16844 // Can't shuffle using an illegal type.
16845 if (!TLI.isTypeLegal(WideVecVT))
16846 return SDValue();
16847
16848 SDValue Shuff = DAG.getVectorShuffle(
16849 WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec);
16850 // At this point all of the data is stored at the bottom of the
16851 // register. We now need to save it to mem.
16852
16853 // Find the largest store unit
16854 MVT StoreType = MVT::i8;
16855 for (MVT Tp : MVT::integer_valuetypes()) {
16856 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
16857 StoreType = Tp;
16858 }
16859 // Didn't find a legal store type.
16860 if (!TLI.isTypeLegal(StoreType))
16861 return SDValue();
16862
16863 // Bitcast the original vector into a vector of store-size units
16864 EVT StoreVecVT =
16865 EVT::getVectorVT(*DAG.getContext(), StoreType,
16866 VT.getSizeInBits() / EVT(StoreType).getSizeInBits());
16867 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16868 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
16870 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
16871 TLI.getPointerTy(DAG.getDataLayout()));
16872 SDValue BasePtr = St->getBasePtr();
16873
16874 // Perform one or more big stores into memory.
16875 unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits();
16876 for (unsigned I = 0; I < E; I++) {
16877 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType,
16878 ShuffWide, DAG.getIntPtrConstant(I, DL));
16879 SDValue Ch =
16880 DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(),
16881 St->getAlign(), St->getMemOperand()->getFlags());
16882 BasePtr =
16883 DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment);
16884 Chains.push_back(Ch);
16885 }
16886 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
16887}
16888
16889// Try taking a single vector store from an fpround (which would otherwise turn
16890// into an expensive buildvector) and splitting it into a series of narrowing
16891// stores.
16893 SelectionDAG &DAG) {
16894 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16895 return SDValue();
16896 SDValue Trunc = St->getValue();
16897 if (Trunc->getOpcode() != ISD::FP_ROUND)
16898 return SDValue();
16899 EVT FromVT = Trunc->getOperand(0).getValueType();
16900 EVT ToVT = Trunc.getValueType();
16901 if (!ToVT.isVector())
16902 return SDValue();
16904 EVT ToEltVT = ToVT.getVectorElementType();
16905 EVT FromEltVT = FromVT.getVectorElementType();
16906
16907 if (FromEltVT != MVT::f32 || ToEltVT != MVT::f16)
16908 return SDValue();
16909
16910 unsigned NumElements = 4;
16911 if (FromVT.getVectorNumElements() % NumElements != 0)
16912 return SDValue();
16913
16914 // Test if the Trunc will be convertible to a VMOVN with a shuffle, and if so
16915 // use the VMOVN over splitting the store. We are looking for patterns of:
16916 // !rev: 0 N 1 N+1 2 N+2 ...
16917 // rev: N 0 N+1 1 N+2 2 ...
16918 // The shuffle may either be a single source (in which case N = NumElts/2) or
16919 // two inputs extended with concat to the same size (in which case N =
16920 // NumElts).
16921 auto isVMOVNShuffle = [&](ShuffleVectorSDNode *SVN, bool Rev) {
16922 ArrayRef<int> M = SVN->getMask();
16923 unsigned NumElts = ToVT.getVectorNumElements();
16924 if (SVN->getOperand(1).isUndef())
16925 NumElts /= 2;
16926
16927 unsigned Off0 = Rev ? NumElts : 0;
16928 unsigned Off1 = Rev ? 0 : NumElts;
16929
16930 for (unsigned I = 0; I < NumElts; I += 2) {
16931 if (M[I] >= 0 && M[I] != (int)(Off0 + I / 2))
16932 return false;
16933 if (M[I + 1] >= 0 && M[I + 1] != (int)(Off1 + I / 2))
16934 return false;
16935 }
16936
16937 return true;
16938 };
16939
16940 if (auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Trunc.getOperand(0)))
16941 if (isVMOVNShuffle(Shuffle, false) || isVMOVNShuffle(Shuffle, true))
16942 return SDValue();
16943
16944 LLVMContext &C = *DAG.getContext();
16945 SDLoc DL(St);
16946 // Details about the old store
16947 SDValue Ch = St->getChain();
16948 SDValue BasePtr = St->getBasePtr();
16949 Align Alignment = St->getBaseAlign();
16950 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
16951 AAMDNodes AAInfo = St->getAAInfo();
16952
16953 // We split the store into slices of NumElements. fp16 trunc stores are vcvt
16954 // and then stored as truncating integer stores.
16955 EVT NewFromVT = EVT::getVectorVT(C, FromEltVT, NumElements);
16956 EVT NewToVT = EVT::getVectorVT(
16957 C, EVT::getIntegerVT(C, ToEltVT.getSizeInBits()), NumElements);
16958
16960 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
16961 unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8;
16962 SDValue NewPtr =
16963 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(NewOffset));
16964
16965 SDValue Extract =
16966 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0),
16967 DAG.getConstant(i * NumElements, DL, MVT::i32));
16968
16969 SDValue FPTrunc =
16970 DAG.getNode(ARMISD::VCVTN, DL, MVT::v8f16, DAG.getUNDEF(MVT::v8f16),
16971 Extract, DAG.getConstant(0, DL, MVT::i32));
16972 Extract = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v4i32, FPTrunc);
16973
16975 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
16976 NewToVT, Alignment, MMOFlags, AAInfo);
16977 Stores.push_back(Store);
16978 }
16979 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
16980}
16981
16982// Try taking a single vector store from an MVETRUNC (which would otherwise turn
16983// into an expensive buildvector) and splitting it into a series of narrowing
16984// stores.
16986 SelectionDAG &DAG) {
16987 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16988 return SDValue();
16989 SDValue Trunc = St->getValue();
16990 if (Trunc->getOpcode() != ARMISD::MVETRUNC)
16991 return SDValue();
16992 EVT FromVT = Trunc->getOperand(0).getValueType();
16993 EVT ToVT = Trunc.getValueType();
16994
16995 LLVMContext &C = *DAG.getContext();
16996 SDLoc DL(St);
16997 // Details about the old store
16998 SDValue Ch = St->getChain();
16999 SDValue BasePtr = St->getBasePtr();
17000 Align Alignment = St->getBaseAlign();
17001 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
17002 AAMDNodes AAInfo = St->getAAInfo();
17003
17004 EVT NewToVT = EVT::getVectorVT(C, ToVT.getVectorElementType(),
17005 FromVT.getVectorNumElements());
17006
17008 for (unsigned i = 0; i < Trunc.getNumOperands(); i++) {
17009 unsigned NewOffset =
17010 i * FromVT.getVectorNumElements() * ToVT.getScalarSizeInBits() / 8;
17011 SDValue NewPtr =
17012 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(NewOffset));
17013
17014 SDValue Extract = Trunc.getOperand(i);
17016 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
17017 NewToVT, Alignment, MMOFlags, AAInfo);
17018 Stores.push_back(Store);
17019 }
17020 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
17021}
17022
17023// Given a floating point store from an extracted vector, with an integer
17024// VGETLANE that already exists, store the existing VGETLANEu directly. This can
17025// help reduce fp register pressure, doesn't require the fp extract and allows
17026// use of more integer post-inc stores not available with vstr.
17028 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
17029 return SDValue();
17030 SDValue Extract = St->getValue();
17031 EVT VT = Extract.getValueType();
17032 // For now only uses f16. This may be useful for f32 too, but that will
17033 // be bitcast(extract), not the VGETLANEu we currently check here.
17034 if (VT != MVT::f16 || Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17035 return SDValue();
17036
17037 SDNode *GetLane =
17038 DAG.getNodeIfExists(ARMISD::VGETLANEu, DAG.getVTList(MVT::i32),
17039 {Extract.getOperand(0), Extract.getOperand(1)});
17040 if (!GetLane)
17041 return SDValue();
17042
17043 LLVMContext &C = *DAG.getContext();
17044 SDLoc DL(St);
17045 // Create a new integer store to replace the existing floating point version.
17046 SDValue Ch = St->getChain();
17047 SDValue BasePtr = St->getBasePtr();
17048 Align Alignment = St->getBaseAlign();
17049 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
17050 AAMDNodes AAInfo = St->getAAInfo();
17051 EVT NewToVT = EVT::getIntegerVT(C, VT.getSizeInBits());
17052 SDValue Store = DAG.getTruncStore(Ch, DL, SDValue(GetLane, 0), BasePtr,
17053 St->getPointerInfo(), NewToVT, Alignment,
17054 MMOFlags, AAInfo);
17055
17056 return Store;
17057}
17058
17059// Combine stores of all VECTOR_INTERLEAVE results into a structured store
17060// (vstN) when they access consecutive memory. Running this after type
17061// legalization let wider vector types to be split into legal types, so each
17062// split can form a structured store.
17065 const ARMSubtarget *Subtarget) {
17067 return SDValue();
17068
17069 if (!ISD::isNormalStore(ST) || !ST->isSimple() || !ST->getOffset().isUndef())
17070 return SDValue();
17071
17072 SDValue StoredValue = ST->getValue();
17073 SDNode *Interleave = StoredValue.getNode();
17074 if (Interleave->getOpcode() != ISD::VECTOR_INTERLEAVE)
17075 return SDValue();
17076
17077 unsigned NumParts = Interleave->getNumOperands();
17079 return SDValue();
17080
17081 if (NumParts == 3 && Subtarget->hasMVEIntegerOps())
17082 return SDValue();
17083
17084 EVT SubVecTy = Interleave->getValueType(0);
17085 if (Subtarget->hasNEON() && !SubVecTy.is64BitVector() &&
17086 !SubVecTy.is128BitVector())
17087 return SDValue();
17088 if (Subtarget->hasMVEIntegerOps() && !SubVecTy.is128BitVector())
17089 return SDValue();
17090 unsigned EltBits = SubVecTy.getScalarSizeInBits();
17091 if (EltBits != 8 && EltBits != 16 && EltBits != 32)
17092 return SDValue();
17093
17094 SmallVector<StoreSDNode *, 4> Stores(NumParts, nullptr);
17095 for (SDUse &Use : Interleave->uses()) {
17096 unsigned ResNo = Use.getResNo();
17098 if (Stores[ResNo] || !Store)
17099 return SDValue();
17100 Stores[ResNo] = Store;
17101 }
17102
17103 if (llvm::is_contained(Stores, nullptr))
17104 return SDValue();
17105
17106 StoreSDNode *BaseStore = Stores[0];
17107 if (Subtarget->hasMVEIntegerOps() && BaseStore->getAlign() < EltBits / 8)
17108 return SDValue();
17109 unsigned Bytes = SubVecTy.getStoreSize().getFixedValue();
17110 for (auto [Idx, Store] : enumerate(Stores)) {
17111 if (!DAG.areNonVolatileConsecutiveStores(Store, BaseStore, Bytes, Idx))
17112 return SDValue();
17113 }
17114
17115 static constexpr Intrinsic::ID NEONStores[] = {Intrinsic::arm_neon_vst2,
17116 Intrinsic::arm_neon_vst3,
17117 Intrinsic::arm_neon_vst4};
17118 SDLoc DL(Interleave);
17120
17121 Ops.push_back(BaseStore->getChain());
17122 Intrinsic::ID IID = 0;
17123 if (Subtarget->hasNEON())
17124 IID = NEONStores[NumParts - 2];
17125 else
17126 IID = NumParts == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q;
17127
17128 Ops.push_back(DAG.getTargetConstant(IID, DL, MVT::i64));
17129
17130 Ops.push_back(BaseStore->getBasePtr());
17131 Ops.append(Interleave->op_begin(), Interleave->op_end());
17132 Ops.push_back(DAG.getConstant(BaseStore->getAlign().value(), DL, MVT::i32));
17133
17134 EVT MemVT =
17135 EVT::getVectorVT(*DAG.getContext(), SubVecTy.getVectorElementType(),
17136 SubVecTy.getVectorElementCount() * NumParts);
17138 MachineMemOperand *MMO =
17139 MF.getMachineMemOperand(BaseStore->getMemOperand(), 0, NumParts * Bytes);
17140 SDValue NewStore;
17141 if (Subtarget->hasNEON()) {
17142 NewStore = DAG.getMemIntrinsicNode(
17143 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
17144 } else {
17145 // MVE
17146 for (unsigned Stage = 0; Stage < NumParts; Stage++) {
17147 Ops.back() = DAG.getConstant(Stage, DL, MVT::i32);
17148 NewStore = DAG.getMemIntrinsicNode(
17149 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
17150 Ops.front() = NewStore;
17151 }
17152 }
17153 for (StoreSDNode *Store : Stores) {
17154 DAG.makeEquivalentMemoryOrdering(SDValue(Store, 0), NewStore);
17155 if (Store != ST)
17156 DCI.CombineTo(Store, NewStore);
17157 }
17158 return NewStore;
17159}
17160
17161static bool
17163 if (N->getOpcode() != ISD::CONCAT_VECTORS)
17164 return false;
17165
17166 unsigned NumParts = N->getNumOperands();
17167
17168 // We should be concatenating each sequential result from a
17169 // VECTOR_INTERLEAVE.
17170 SDNode *InterleaveOp = N->getOperand(0).getNode();
17171 if (InterleaveOp->getOpcode() != ISD::VECTOR_INTERLEAVE ||
17172 InterleaveOp->getNumOperands() != NumParts)
17173 return false;
17174
17175 for (unsigned I = 0; I < NumParts; I++)
17176 if (N->getOperand(I) != SDValue(InterleaveOp, I))
17177 return false;
17178
17179 Ops.append(InterleaveOp->op_begin(), InterleaveOp->op_end());
17180 return true;
17181}
17182
17185 const ARMSubtarget *Subtarget) {
17186 if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps())
17187 return SDValue();
17188 if (SDValue Res =
17190 return Res;
17191
17192 if (!DCI.isBeforeLegalize())
17193 return SDValue();
17194
17195 if (!ISD::isNormalStore(ST) || !ST->isSimple() || !ST->getOffset().isUndef())
17196 return SDValue();
17197
17198 SDValue WideValue = ST->getValue();
17199 SmallVector<SDValue, 4> ValueInterleaveOps;
17201 ValueInterleaveOps))
17202 return SDValue();
17203
17204 if (!WideValue.hasOneUse())
17205 return SDValue();
17206
17207 unsigned NumParts = ValueInterleaveOps.size();
17208 if (NumParts != 2 && NumParts != 3 && NumParts != 4)
17209 return SDValue();
17210
17211 if (NumParts == 3 && Subtarget->hasMVEIntegerOps())
17212 return SDValue();
17213
17214 EVT SubVecTy = ValueInterleaveOps[0].getValueType();
17215 if (Subtarget->hasNEON() && !SubVecTy.is64BitVector() &&
17216 !SubVecTy.is128BitVector())
17217 return SDValue();
17218 if (Subtarget->hasMVEIntegerOps() && !SubVecTy.is128BitVector())
17219 return SDValue();
17220 unsigned EltBits = SubVecTy.getScalarSizeInBits();
17221 if (EltBits != 8 && EltBits != 16 && EltBits != 32)
17222 return SDValue();
17223 if (Subtarget->hasMVEIntegerOps() && ST->getAlign() < EltBits / 8)
17224 return SDValue();
17225 static constexpr Intrinsic::ID NEONStores[] = {Intrinsic::arm_neon_vst2,
17226 Intrinsic::arm_neon_vst3,
17227 Intrinsic::arm_neon_vst4};
17228 SDLoc DL(ST);
17230 Ops.push_back(ST->getChain());
17231 Intrinsic::ID IID = 0;
17232 if (Subtarget->hasNEON())
17233 IID = NEONStores[NumParts - 2];
17234 else
17235 IID = NumParts == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q;
17236
17237 Ops.push_back(DAG.getTargetConstant(IID, DL, MVT::i64));
17238
17239 Ops.push_back(ST->getBasePtr());
17240 Ops.append(ValueInterleaveOps);
17241
17242 Ops.push_back(DAG.getConstant(ST->getAlign().value(), DL, MVT::i32));
17243 if (Subtarget->hasNEON())
17245 DAG.getVTList(MVT::Other), Ops,
17246 ST->getMemoryVT(), ST->getMemOperand());
17247 // MVE
17248 SDValue NewStore;
17249 for (unsigned Stage = 0; Stage < NumParts; Stage++) {
17250 Ops.back() = DAG.getConstant(Stage, DL, MVT::i32);
17252 DAG.getVTList(MVT::Other), Ops,
17253 ST->getMemoryVT(), ST->getMemOperand());
17254 Ops.front() = NewStore;
17255 }
17256 return NewStore;
17257}
17258
17260 const ARMSubtarget *Subtarget) {
17261 SDValue Val = St->getValue();
17262 EVT VT = Val.getValueType();
17263 if (!Subtarget->isLittle() || !VT.isVector() ||
17264 VT.getVectorNumElements() > 4 || VT.getScalarType() != MVT::i32 ||
17265 St->isVolatile() || !ISD::isNormalStore(St) || !Val.hasOneUse() ||
17267 return SDValue();
17268
17269 // We are looking for a build vector of constants that will not be lowered to
17270 // a splat.
17271 unsigned Cost = 0;
17272 SmallSet<unsigned, 4> ImmSet;
17273 for (unsigned I = 0; I < VT.getVectorNumElements(); I++) {
17274 auto *C = dyn_cast<ConstantSDNode>(Val.getOperand(I));
17275 if (!C)
17276 return SDValue();
17277 if (!ImmSet.insert(C->getZExtValue()).second)
17278 continue;
17279 Cost += ConstantMaterializationCost(C->getZExtValue(), Subtarget,
17280 Subtarget->hasMinSize());
17281 if (Cost > 4)
17282 return SDValue();
17283 }
17284 if (ImmSet.size() == 1) // Don't include splats
17285 return SDValue();
17286
17287 // Look for a simple single block loop, we can hoist the vector load out in
17288 // that case.
17289 const BasicBlock *Block = DAG.getBasicBlock();
17290 assert(Block && "Expected a valid block!");
17292 return SDValue();
17293
17294 SDValue Chain = St->getChain();
17295 SDLoc DL(St);
17296
17297 for (unsigned I = 0; I < VT.getVectorNumElements(); I++) {
17298 unsigned Offset = I * VT.getScalarStoreSize();
17299 SDValue OffsetPtr = DAG.getObjectPtrOffset(
17300 DL, St->getBasePtr(), DAG.getConstant(Offset, DL, MVT::i32));
17301 Chain = DAG.getStore(Chain, DL, Val.getOperand(I), OffsetPtr,
17302 St->getPointerInfo().getWithOffset(Offset),
17303 commonAlignment(St->getBaseAlign(), Offset),
17304 St->getMemOperand()->getFlags(), St->getAAInfo());
17305 }
17306
17307 return Chain;
17308}
17309
17310/// PerformSTORECombine - Target-specific dag combine xforms for
17311/// ISD::STORE.
17314 const ARMSubtarget *Subtarget) {
17316 if (St->isVolatile())
17317 return SDValue();
17318 SDValue StVal = St->getValue();
17319 EVT VT = StVal.getValueType();
17320 if (SDValue Store =
17322 return Store;
17323
17324 if (Subtarget->hasNEON())
17326 return Store;
17327
17328 if (Subtarget->hasMVEFloatOps())
17329 if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG))
17330 return NewToken;
17331
17332 if (Subtarget->hasMVEIntegerOps()) {
17333 if (SDValue NewChain = PerformExtractFpToIntStores(St, DCI.DAG))
17334 return NewChain;
17335 if (SDValue NewToken =
17337 return NewToken;
17338 }
17339
17340 if (!ISD::isNormalStore(St))
17341 return SDValue();
17342
17343 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
17344 // ARM stores of arguments in the same cache line.
17345 if (StVal.getOpcode() == ARMISD::VMOVDRR && StVal->hasOneUse()) {
17346 SelectionDAG &DAG = DCI.DAG;
17347 bool isBigEndian = DAG.getDataLayout().isBigEndian();
17348 SDLoc DL(St);
17349 SDValue BasePtr = St->getBasePtr();
17350 SDValue NewST1 =
17351 DAG.getStore(St->getChain(), DL, StVal.getOperand(isBigEndian ? 1 : 0),
17352 BasePtr, St->getPointerInfo(), St->getBaseAlign(),
17353 St->getMemOperand()->getFlags());
17354
17355 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
17356 DAG.getConstant(4, DL, MVT::i32));
17357 return DAG.getStore(NewST1.getValue(0), DL,
17358 StVal.getOperand(isBigEndian ? 0 : 1), OffsetPtr,
17359 St->getPointerInfo().getWithOffset(4),
17360 St->getBaseAlign(), St->getMemOperand()->getFlags());
17361 }
17362
17363 if (StVal.getValueType() == MVT::i64 &&
17365 // Bitcast an i64 store extracted from a vector to f64.
17366 // Otherwise, the i64 value will be legalized to a pair of i32 values.
17367 SelectionDAG &DAG = DCI.DAG;
17368 SDLoc dl(StVal);
17369 SDValue IntVec = StVal.getOperand(0);
17370 EVT FloatVT =
17371 EVT::getVectorVT(*DAG.getContext(), MVT::f64,
17373 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
17374 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Vec,
17375 StVal.getOperand(1));
17376 dl = SDLoc(N);
17377 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
17378 // Make the DAGCombiner fold the bitcasts.
17379 DCI.AddToWorklist(Vec.getNode());
17380 DCI.AddToWorklist(ExtElt.getNode());
17381 DCI.AddToWorklist(V.getNode());
17382 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
17383 St->getPointerInfo(), St->getAlign(),
17384 St->getMemOperand()->getFlags(), St->getAAInfo());
17385 }
17386
17388 return S;
17389
17390 // If this is a legal vector store, try to combine it into a VST1_UPD.
17391 if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() &&
17393 return CombineBaseUpdate(N, DCI);
17394
17395 return SDValue();
17396}
17397
17398/// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
17399/// can replace combinations of VMUL and VCVT (floating-point to integer)
17400/// when the VMUL has a constant operand that is a power of 2.
17401///
17402/// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
17403/// vmul.f32 d16, d17, d16
17404/// vcvt.s32.f32 d16, d16
17405/// becomes:
17406/// vcvt.s32.f32 d16, d16, #3
17408 const ARMSubtarget *Subtarget) {
17409 if (!Subtarget->hasNEON())
17410 return SDValue();
17411
17412 SDValue Op = N->getOperand(0);
17413 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
17414 Op.getOpcode() != ISD::FMUL)
17415 return SDValue();
17416
17417 SDValue ConstVec = Op->getOperand(1);
17418 if (!isa<BuildVectorSDNode>(ConstVec))
17419 return SDValue();
17420
17421 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
17422 uint32_t FloatBits = FloatTy.getSizeInBits();
17423 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
17424 uint32_t IntBits = IntTy.getSizeInBits();
17425 unsigned NumLanes = Op.getValueType().getVectorNumElements();
17426 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
17427 // These instructions only exist converting from f32 to i32. We can handle
17428 // smaller integers by generating an extra truncate, but larger ones would
17429 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
17430 // these instructions only support v2i32/v4i32 types.
17431 return SDValue();
17432 }
17433
17434 BitVector UndefElements;
17436 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
17437 if (C == -1 || C == 0 || C > 32)
17438 return SDValue();
17439
17440 SDLoc dl(N);
17441 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
17442 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
17443 Intrinsic::arm_neon_vcvtfp2fxu;
17444 SDValue FixConv = DAG.getNode(
17445 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
17446 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
17447 DAG.getConstant(C, dl, MVT::i32));
17448
17449 if (IntBits < FloatBits)
17450 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
17451
17452 return FixConv;
17453}
17454
17456 const ARMSubtarget *Subtarget) {
17457 if (!Subtarget->hasMVEFloatOps())
17458 return SDValue();
17459
17460 // Turn (fadd x, (vselect c, y, -0.0)) into (vselect c, (fadd x, y), x)
17461 // The second form can be more easily turned into a predicated vadd, and
17462 // possibly combined into a fma to become a predicated vfma.
17463 SDValue Op0 = N->getOperand(0);
17464 SDValue Op1 = N->getOperand(1);
17465 EVT VT = N->getValueType(0);
17466 SDLoc DL(N);
17467
17468 // The identity element for a fadd is -0.0 or +0.0 when the nsz flag is set,
17469 // which these VMOV's represent.
17470 auto isIdentitySplat = [&](SDValue Op, bool NSZ) {
17471 if (Op.getOpcode() != ISD::BITCAST ||
17472 Op.getOperand(0).getOpcode() != ARMISD::VMOVIMM)
17473 return false;
17474 uint64_t ImmVal = Op.getOperand(0).getConstantOperandVal(0);
17475 if (VT == MVT::v4f32 && (ImmVal == 1664 || (ImmVal == 0 && NSZ)))
17476 return true;
17477 if (VT == MVT::v8f16 && (ImmVal == 2688 || (ImmVal == 0 && NSZ)))
17478 return true;
17479 return false;
17480 };
17481
17482 if (Op0.getOpcode() == ISD::VSELECT && Op1.getOpcode() != ISD::VSELECT)
17483 std::swap(Op0, Op1);
17484
17485 if (Op1.getOpcode() != ISD::VSELECT)
17486 return SDValue();
17487
17488 SDNodeFlags FaddFlags = N->getFlags();
17489 bool NSZ = FaddFlags.hasNoSignedZeros();
17490 if (!isIdentitySplat(Op1.getOperand(2), NSZ))
17491 return SDValue();
17492
17493 SDValue FAdd =
17494 DAG.getNode(ISD::FADD, DL, VT, Op0, Op1.getOperand(1), FaddFlags);
17495 return DAG.getNode(ISD::VSELECT, DL, VT, Op1.getOperand(0), FAdd, Op0, FaddFlags);
17496}
17497
17499 SDValue LHS = N->getOperand(0);
17500 SDValue RHS = N->getOperand(1);
17501 EVT VT = N->getValueType(0);
17502 SDLoc DL(N);
17503
17504 if (!N->getFlags().hasAllowReassociation())
17505 return SDValue();
17506
17507 // Combine fadd(a, vcmla(b, c, d)) -> vcmla(fadd(a, b), b, c)
17508 auto ReassocComplex = [&](SDValue A, SDValue B) {
17509 if (A.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
17510 return SDValue();
17511 unsigned Opc = A.getConstantOperandVal(0);
17512 if (Opc != Intrinsic::arm_mve_vcmlaq)
17513 return SDValue();
17514 SDValue VCMLA = DAG.getNode(
17515 ISD::INTRINSIC_WO_CHAIN, DL, VT, A.getOperand(0), A.getOperand(1),
17516 DAG.getNode(ISD::FADD, DL, VT, A.getOperand(2), B, N->getFlags()),
17517 A.getOperand(3), A.getOperand(4));
17518 VCMLA->setFlags(A->getFlags());
17519 return VCMLA;
17520 };
17521 if (SDValue R = ReassocComplex(LHS, RHS))
17522 return R;
17523 if (SDValue R = ReassocComplex(RHS, LHS))
17524 return R;
17525
17526 return SDValue();
17527}
17528
17530 const ARMSubtarget *Subtarget) {
17532 return S;
17533 if (SDValue S = PerformFADDVCMLACombine(N, DAG))
17534 return S;
17535 return SDValue();
17536}
17537
17538/// PerformVMulVCTPCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
17539/// can replace combinations of VCVT (integer to floating-point) and VMUL
17540/// when the VMUL has a constant operand that is a power of 2.
17541///
17542/// Example (assume d17 = <float 0.125, float 0.125>):
17543/// vcvt.f32.s32 d16, d16
17544/// vmul.f32 d16, d16, d17
17545/// becomes:
17546/// vcvt.f32.s32 d16, d16, #3
17548 const ARMSubtarget *Subtarget) {
17549 if (!Subtarget->hasNEON())
17550 return SDValue();
17551
17552 SDValue Op = N->getOperand(0);
17553 unsigned OpOpcode = Op.getNode()->getOpcode();
17554 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
17555 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
17556 return SDValue();
17557
17558 SDValue ConstVec = N->getOperand(1);
17559 if (!isa<BuildVectorSDNode>(ConstVec))
17560 return SDValue();
17561
17562 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
17563 uint32_t FloatBits = FloatTy.getSizeInBits();
17564 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
17565 uint32_t IntBits = IntTy.getSizeInBits();
17566 unsigned NumLanes = Op.getValueType().getVectorNumElements();
17567 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
17568 // These instructions only exist converting from i32 to f32. We can handle
17569 // smaller integers by generating an extra extend, but larger ones would
17570 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
17571 // these instructions only support v2i32/v4i32 types.
17572 return SDValue();
17573 }
17574
17575 ConstantFPSDNode *CN = isConstOrConstSplatFP(ConstVec, true);
17576 APFloat Recip(0.0f);
17577 if (!CN || !CN->getValueAPF().getExactInverse(&Recip))
17578 return SDValue();
17579
17580 bool IsExact;
17581 APSInt IntVal(33);
17582 if (Recip.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
17583 APFloat::opOK ||
17584 !IsExact)
17585 return SDValue();
17586
17587 int32_t C = IntVal.exactLogBase2();
17588 if (C == -1 || C == 0 || C > 32)
17589 return SDValue();
17590
17591 SDLoc DL(N);
17592 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
17593 SDValue ConvInput = Op.getOperand(0);
17594 if (IntBits < FloatBits)
17596 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, ConvInput);
17597
17598 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp
17599 : Intrinsic::arm_neon_vcvtfxu2fp;
17600 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
17601 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
17602 DAG.getConstant(C, DL, MVT::i32));
17603}
17604
17606 const ARMSubtarget *ST) {
17607 if (!ST->hasMVEIntegerOps())
17608 return SDValue();
17609
17610 assert(N->getOpcode() == ISD::VECREDUCE_ADD);
17611 EVT ResVT = N->getValueType(0);
17612 SDValue N0 = N->getOperand(0);
17613 SDLoc dl(N);
17614
17615 // Try to turn vecreduce_add(add(x, y)) into vecreduce(x) + vecreduce(y)
17616 if (ResVT == MVT::i32 && N0.getOpcode() == ISD::ADD &&
17617 (N0.getValueType() == MVT::v4i32 || N0.getValueType() == MVT::v8i16 ||
17618 N0.getValueType() == MVT::v16i8)) {
17619 SDValue Red0 = DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, N0.getOperand(0));
17620 SDValue Red1 = DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, N0.getOperand(1));
17621 return DAG.getNode(ISD::ADD, dl, ResVT, Red0, Red1);
17622 }
17623
17624 // We are looking for something that will have illegal types if left alone,
17625 // but that we can convert to a single instruction under MVE. For example
17626 // vecreduce_add(sext(A, v8i32)) => VADDV.s16 A
17627 // or
17628 // vecreduce_add(mul(zext(A, v16i32), zext(B, v16i32))) => VMLADAV.u8 A, B
17629
17630 // The legal cases are:
17631 // VADDV u/s 8/16/32
17632 // VMLAV u/s 8/16/32
17633 // VADDLV u/s 32
17634 // VMLALV u/s 16/32
17635
17636 // If the input vector is smaller than legal (v4i8/v4i16 for example) we can
17637 // extend it and use v4i32 instead.
17638 auto ExtTypeMatches = [](SDValue A, ArrayRef<MVT> ExtTypes) {
17639 EVT AVT = A.getValueType();
17640 return any_of(ExtTypes, [&](MVT Ty) {
17641 return AVT.getVectorNumElements() == Ty.getVectorNumElements() &&
17642 AVT.bitsLE(Ty);
17643 });
17644 };
17645 auto ExtendIfNeeded = [&](SDValue A, unsigned ExtendCode) {
17646 EVT AVT = A.getValueType();
17647 if (!AVT.is128BitVector())
17648 A = DAG.getNode(
17649 ExtendCode, dl,
17651 *DAG.getContext(),
17653 A);
17654 return A;
17655 };
17656 auto IsVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes) {
17657 if (ResVT != RetTy || N0->getOpcode() != ExtendCode)
17658 return SDValue();
17659 SDValue A = N0->getOperand(0);
17660 if (ExtTypeMatches(A, ExtTypes))
17661 return ExtendIfNeeded(A, ExtendCode);
17662 return SDValue();
17663 };
17664 auto IsPredVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
17665 SDValue &Mask) {
17666 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
17668 return SDValue();
17669 Mask = N0->getOperand(0);
17670 SDValue Ext = N0->getOperand(1);
17671 if (Ext->getOpcode() != ExtendCode)
17672 return SDValue();
17673 SDValue A = Ext->getOperand(0);
17674 if (ExtTypeMatches(A, ExtTypes))
17675 return ExtendIfNeeded(A, ExtendCode);
17676 return SDValue();
17677 };
17678 auto IsVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
17679 SDValue &A, SDValue &B) {
17680 // For a vmla we are trying to match a larger pattern:
17681 // ExtA = sext/zext A
17682 // ExtB = sext/zext B
17683 // Mul = mul ExtA, ExtB
17684 // vecreduce.add Mul
17685 // There might also be en extra extend between the mul and the addreduce, so
17686 // long as the bitwidth is high enough to make them equivalent (for example
17687 // original v8i16 might be mul at v8i32 and the reduce happens at v8i64).
17688 if (ResVT != RetTy)
17689 return false;
17690 SDValue Mul = N0;
17691 if (Mul->getOpcode() == ExtendCode &&
17692 Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
17693 ResVT.getScalarSizeInBits())
17694 Mul = Mul->getOperand(0);
17695 if (Mul->getOpcode() != ISD::MUL)
17696 return false;
17697 SDValue ExtA = Mul->getOperand(0);
17698 SDValue ExtB = Mul->getOperand(1);
17699 if (ExtA->getOpcode() != ExtendCode || ExtB->getOpcode() != ExtendCode)
17700 return false;
17701 A = ExtA->getOperand(0);
17702 B = ExtB->getOperand(0);
17703 if (ExtTypeMatches(A, ExtTypes) && ExtTypeMatches(B, ExtTypes)) {
17704 A = ExtendIfNeeded(A, ExtendCode);
17705 B = ExtendIfNeeded(B, ExtendCode);
17706 return true;
17707 }
17708 return false;
17709 };
17710 auto IsPredVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
17711 SDValue &A, SDValue &B, SDValue &Mask) {
17712 // Same as the pattern above with a select for the zero predicated lanes
17713 // ExtA = sext/zext A
17714 // ExtB = sext/zext B
17715 // Mul = mul ExtA, ExtB
17716 // N0 = select Mask, Mul, 0
17717 // vecreduce.add N0
17718 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
17720 return false;
17721 Mask = N0->getOperand(0);
17722 SDValue Mul = N0->getOperand(1);
17723 if (Mul->getOpcode() == ExtendCode &&
17724 Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
17725 ResVT.getScalarSizeInBits())
17726 Mul = Mul->getOperand(0);
17727 if (Mul->getOpcode() != ISD::MUL)
17728 return false;
17729 SDValue ExtA = Mul->getOperand(0);
17730 SDValue ExtB = Mul->getOperand(1);
17731 if (ExtA->getOpcode() != ExtendCode || ExtB->getOpcode() != ExtendCode)
17732 return false;
17733 A = ExtA->getOperand(0);
17734 B = ExtB->getOperand(0);
17735 if (ExtTypeMatches(A, ExtTypes) && ExtTypeMatches(B, ExtTypes)) {
17736 A = ExtendIfNeeded(A, ExtendCode);
17737 B = ExtendIfNeeded(B, ExtendCode);
17738 return true;
17739 }
17740 return false;
17741 };
17742 auto Create64bitNode = [&](unsigned Opcode, ArrayRef<SDValue> Ops) {
17743 // Split illegal MVT::v16i8->i64 vector reductions into two legal v8i16->i64
17744 // reductions. The operands are extended with MVEEXT, but as they are
17745 // reductions the lane orders do not matter. MVEEXT may be combined with
17746 // loads to produce two extending loads, or else they will be expanded to
17747 // VREV/VMOVL.
17748 EVT VT = Ops[0].getValueType();
17749 if (VT == MVT::v16i8) {
17750 assert((Opcode == ARMISD::VMLALVs || Opcode == ARMISD::VMLALVu) &&
17751 "Unexpected illegal long reduction opcode");
17752 bool IsUnsigned = Opcode == ARMISD::VMLALVu;
17753
17754 SDValue Ext0 =
17755 DAG.getNode(IsUnsigned ? ARMISD::MVEZEXT : ARMISD::MVESEXT, dl,
17756 DAG.getVTList(MVT::v8i16, MVT::v8i16), Ops[0]);
17757 SDValue Ext1 =
17758 DAG.getNode(IsUnsigned ? ARMISD::MVEZEXT : ARMISD::MVESEXT, dl,
17759 DAG.getVTList(MVT::v8i16, MVT::v8i16), Ops[1]);
17760
17761 SDValue MLA0 = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
17762 Ext0, Ext1);
17763 SDValue MLA1 =
17764 DAG.getNode(IsUnsigned ? ARMISD::VMLALVAu : ARMISD::VMLALVAs, dl,
17765 DAG.getVTList(MVT::i32, MVT::i32), MLA0, MLA0.getValue(1),
17766 Ext0.getValue(1), Ext1.getValue(1));
17767 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, MLA1, MLA1.getValue(1));
17768 }
17769 SDValue Node = DAG.getNode(Opcode, dl, {MVT::i32, MVT::i32}, Ops);
17770 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Node,
17771 SDValue(Node.getNode(), 1));
17772 };
17773
17774 SDValue A, B;
17775 SDValue Mask;
17776 if (IsVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
17777 return DAG.getNode(ARMISD::VMLAVs, dl, ResVT, A, B);
17778 if (IsVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
17779 return DAG.getNode(ARMISD::VMLAVu, dl, ResVT, A, B);
17780 if (IsVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v16i8, MVT::v8i16, MVT::v4i32},
17781 A, B))
17782 return Create64bitNode(ARMISD::VMLALVs, {A, B});
17783 if (IsVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v16i8, MVT::v8i16, MVT::v4i32},
17784 A, B))
17785 return Create64bitNode(ARMISD::VMLALVu, {A, B});
17786 if (IsVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B))
17787 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17788 DAG.getNode(ARMISD::VMLAVs, dl, MVT::i32, A, B));
17789 if (IsVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B))
17790 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17791 DAG.getNode(ARMISD::VMLAVu, dl, MVT::i32, A, B));
17792
17793 if (IsPredVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B,
17794 Mask))
17795 return DAG.getNode(ARMISD::VMLAVps, dl, ResVT, A, B, Mask);
17796 if (IsPredVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B,
17797 Mask))
17798 return DAG.getNode(ARMISD::VMLAVpu, dl, ResVT, A, B, Mask);
17799 if (IsPredVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B,
17800 Mask))
17801 return Create64bitNode(ARMISD::VMLALVps, {A, B, Mask});
17802 if (IsPredVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B,
17803 Mask))
17804 return Create64bitNode(ARMISD::VMLALVpu, {A, B, Mask});
17805 if (IsPredVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B, Mask))
17806 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17807 DAG.getNode(ARMISD::VMLAVps, dl, MVT::i32, A, B, Mask));
17808 if (IsPredVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B, Mask))
17809 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17810 DAG.getNode(ARMISD::VMLAVpu, dl, MVT::i32, A, B, Mask));
17811
17812 if (SDValue A = IsVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}))
17813 return DAG.getNode(ARMISD::VADDVs, dl, ResVT, A);
17814 if (SDValue A = IsVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}))
17815 return DAG.getNode(ARMISD::VADDVu, dl, ResVT, A);
17816 if (SDValue A = IsVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}))
17817 return Create64bitNode(ARMISD::VADDLVs, {A});
17818 if (SDValue A = IsVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}))
17819 return Create64bitNode(ARMISD::VADDLVu, {A});
17820 if (SDValue A = IsVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}))
17821 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17822 DAG.getNode(ARMISD::VADDVs, dl, MVT::i32, A));
17823 if (SDValue A = IsVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}))
17824 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17825 DAG.getNode(ARMISD::VADDVu, dl, MVT::i32, A));
17826
17827 if (SDValue A = IsPredVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
17828 return DAG.getNode(ARMISD::VADDVps, dl, ResVT, A, Mask);
17829 if (SDValue A = IsPredVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
17830 return DAG.getNode(ARMISD::VADDVpu, dl, ResVT, A, Mask);
17831 if (SDValue A = IsPredVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}, Mask))
17832 return Create64bitNode(ARMISD::VADDLVps, {A, Mask});
17833 if (SDValue A = IsPredVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}, Mask))
17834 return Create64bitNode(ARMISD::VADDLVpu, {A, Mask});
17835 if (SDValue A = IsPredVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, Mask))
17836 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17837 DAG.getNode(ARMISD::VADDVps, dl, MVT::i32, A, Mask));
17838 if (SDValue A = IsPredVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, Mask))
17839 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17840 DAG.getNode(ARMISD::VADDVpu, dl, MVT::i32, A, Mask));
17841
17842 // Some complications. We can get a case where the two inputs of the mul are
17843 // the same, then the output sext will have been helpfully converted to a
17844 // zext. Turn it back.
17845 SDValue Op = N0;
17846 if (Op->getOpcode() == ISD::VSELECT)
17847 Op = Op->getOperand(1);
17848 if (Op->getOpcode() == ISD::ZERO_EXTEND &&
17849 Op->getOperand(0)->getOpcode() == ISD::MUL) {
17850 SDValue Mul = Op->getOperand(0);
17851 if (Mul->getOperand(0) == Mul->getOperand(1) &&
17852 Mul->getOperand(0)->getOpcode() == ISD::SIGN_EXTEND) {
17853 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, N0->getValueType(0), Mul);
17854 if (Op != N0)
17855 Ext = DAG.getNode(ISD::VSELECT, dl, N0->getValueType(0),
17856 N0->getOperand(0), Ext, N0->getOperand(2));
17857 return DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, Ext);
17858 }
17859 }
17860
17861 return SDValue();
17862}
17863
17864// Looks for vaddv(shuffle) or vmlav(shuffle, shuffle), with a shuffle where all
17865// the lanes are used. Due to the reduction being commutative the shuffle can be
17866// removed.
17868 unsigned VecOp = N->getOperand(0).getValueType().isVector() ? 0 : 2;
17869 auto *Shuf = dyn_cast<ShuffleVectorSDNode>(N->getOperand(VecOp));
17870 if (!Shuf || !Shuf->getOperand(1).isUndef())
17871 return SDValue();
17872
17873 // Check all elements are used once in the mask.
17874 ArrayRef<int> Mask = Shuf->getMask();
17875 APInt SetElts(Mask.size(), 0);
17876 for (int E : Mask) {
17877 if (E < 0 || E >= (int)Mask.size())
17878 return SDValue();
17879 SetElts.setBit(E);
17880 }
17881 if (!SetElts.isAllOnes())
17882 return SDValue();
17883
17884 if (N->getNumOperands() != VecOp + 1) {
17885 auto *Shuf2 = dyn_cast<ShuffleVectorSDNode>(N->getOperand(VecOp + 1));
17886 if (!Shuf2 || !Shuf2->getOperand(1).isUndef() || Shuf2->getMask() != Mask)
17887 return SDValue();
17888 }
17889
17891 for (SDValue Op : N->ops()) {
17892 if (Op.getValueType().isVector())
17893 Ops.push_back(Op.getOperand(0));
17894 else
17895 Ops.push_back(Op);
17896 }
17897 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getVTList(), Ops);
17898}
17899
17902 SDValue Op0 = N->getOperand(0);
17903 SDValue Op1 = N->getOperand(1);
17904 unsigned IsTop = N->getConstantOperandVal(2);
17905
17906 // VMOVNT a undef -> a
17907 // VMOVNB a undef -> a
17908 // VMOVNB undef a -> a
17909 if (Op1->isUndef())
17910 return Op0;
17911 if (Op0->isUndef() && !IsTop)
17912 return Op1;
17913
17914 // VMOVNt(c, VQMOVNb(a, b)) => VQMOVNt(c, b)
17915 // VMOVNb(c, VQMOVNb(a, b)) => VQMOVNb(c, b)
17916 if ((Op1->getOpcode() == ARMISD::VQMOVNs ||
17917 Op1->getOpcode() == ARMISD::VQMOVNu) &&
17918 Op1->getConstantOperandVal(2) == 0)
17919 return DCI.DAG.getNode(Op1->getOpcode(), SDLoc(Op1), N->getValueType(0),
17920 Op0, Op1->getOperand(1), N->getOperand(2));
17921
17922 // Only the bottom lanes from Qm (Op1) and either the top or bottom lanes from
17923 // Qd (Op0) are demanded from a VMOVN, depending on whether we are inserting
17924 // into the top or bottom lanes.
17925 unsigned NumElts = N->getValueType(0).getVectorNumElements();
17926 APInt Op1DemandedElts = APInt::getSplat(NumElts, APInt::getLowBitsSet(2, 1));
17927 APInt Op0DemandedElts =
17928 IsTop ? Op1DemandedElts
17929 : APInt::getSplat(NumElts, APInt::getHighBitsSet(2, 1));
17930
17932 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, DCI))
17933 return SDValue(N, 0);
17934 if (TLI.SimplifyDemandedVectorElts(Op1, Op1DemandedElts, DCI))
17935 return SDValue(N, 0);
17936
17937 return SDValue();
17938}
17939
17942 SDValue Op0 = N->getOperand(0);
17943 unsigned IsTop = N->getConstantOperandVal(2);
17944
17945 unsigned NumElts = N->getValueType(0).getVectorNumElements();
17946 APInt Op0DemandedElts =
17947 APInt::getSplat(NumElts, IsTop ? APInt::getLowBitsSet(2, 1)
17948 : APInt::getHighBitsSet(2, 1));
17949
17951 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, DCI))
17952 return SDValue(N, 0);
17953 return SDValue();
17954}
17955
17958 EVT VT = N->getValueType(0);
17959 SDValue LHS = N->getOperand(0);
17960 SDValue RHS = N->getOperand(1);
17961
17962 auto *Shuf0 = dyn_cast<ShuffleVectorSDNode>(LHS);
17963 auto *Shuf1 = dyn_cast<ShuffleVectorSDNode>(RHS);
17964 // Turn VQDMULH(shuffle, shuffle) -> shuffle(VQDMULH)
17965 if (Shuf0 && Shuf1 && Shuf0->getMask().equals(Shuf1->getMask()) &&
17966 LHS.getOperand(1).isUndef() && RHS.getOperand(1).isUndef() &&
17967 (LHS.hasOneUse() || RHS.hasOneUse() || LHS == RHS)) {
17968 SDLoc DL(N);
17969 SDValue NewBinOp = DCI.DAG.getNode(N->getOpcode(), DL, VT,
17970 LHS.getOperand(0), RHS.getOperand(0));
17971 SDValue UndefV = LHS.getOperand(1);
17972 return DCI.DAG.getVectorShuffle(VT, DL, NewBinOp, UndefV, Shuf0->getMask());
17973 }
17974 return SDValue();
17975}
17976
17978 SDLoc DL(N);
17979 SDValue Op0 = N->getOperand(0);
17980 SDValue Op1 = N->getOperand(1);
17981
17982 // Turn X << -C -> X >> C and viceversa. The negative shifts can come up from
17983 // uses of the intrinsics.
17984 if (auto C = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
17985 int ShiftAmt = C->getSExtValue();
17986 if (ShiftAmt == 0) {
17987 SDValue Merge = DAG.getMergeValues({Op0, Op1}, DL);
17988 DAG.ReplaceAllUsesWith(N, Merge.getNode());
17989 return SDValue();
17990 }
17991
17992 if (ShiftAmt >= -32 && ShiftAmt < 0) {
17993 unsigned NewOpcode =
17994 N->getOpcode() == ARMISD::LSLL ? ARMISD::LSRL : ARMISD::LSLL;
17995 SDValue NewShift = DAG.getNode(NewOpcode, DL, N->getVTList(), Op0, Op1,
17996 DAG.getConstant(-ShiftAmt, DL, MVT::i32));
17997 DAG.ReplaceAllUsesWith(N, NewShift.getNode());
17998 return NewShift;
17999 }
18000 }
18001
18002 return SDValue();
18003}
18004
18005/// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
18007 DAGCombinerInfo &DCI) const {
18008 SelectionDAG &DAG = DCI.DAG;
18009 unsigned IntNo = N->getConstantOperandVal(0);
18010 switch (IntNo) {
18011 default:
18012 // Don't do anything for most intrinsics.
18013 break;
18014
18015 // Vector shifts: check for immediate versions and lower them.
18016 // Note: This is done during DAG combining instead of DAG legalizing because
18017 // the build_vectors for 64-bit vector element shift counts are generally
18018 // not legal, and it is hard to see their values after they get legalized to
18019 // loads from a constant pool.
18020 case Intrinsic::arm_neon_vshifts:
18021 case Intrinsic::arm_neon_vshiftu:
18022 case Intrinsic::arm_neon_vrshifts:
18023 case Intrinsic::arm_neon_vrshiftu:
18024 case Intrinsic::arm_neon_vrshiftn:
18025 case Intrinsic::arm_neon_vqshifts:
18026 case Intrinsic::arm_neon_vqshiftu:
18027 case Intrinsic::arm_neon_vqshiftsu:
18028 case Intrinsic::arm_neon_vqshiftns:
18029 case Intrinsic::arm_neon_vqshiftnu:
18030 case Intrinsic::arm_neon_vqshiftnsu:
18031 case Intrinsic::arm_neon_vqrshiftns:
18032 case Intrinsic::arm_neon_vqrshiftnu:
18033 case Intrinsic::arm_neon_vqrshiftnsu: {
18034 EVT VT = N->getOperand(1).getValueType();
18035 int64_t Cnt;
18036 unsigned VShiftOpc = 0;
18037
18038 switch (IntNo) {
18039 case Intrinsic::arm_neon_vshifts:
18040 case Intrinsic::arm_neon_vshiftu:
18041 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
18042 VShiftOpc = ARMISD::VSHLIMM;
18043 break;
18044 }
18045 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
18046 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
18047 : ARMISD::VSHRuIMM);
18048 break;
18049 }
18050 return SDValue();
18051
18052 case Intrinsic::arm_neon_vrshifts:
18053 case Intrinsic::arm_neon_vrshiftu:
18054 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
18055 break;
18056 return SDValue();
18057
18058 case Intrinsic::arm_neon_vqshifts:
18059 case Intrinsic::arm_neon_vqshiftu:
18060 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
18061 break;
18062 return SDValue();
18063
18064 case Intrinsic::arm_neon_vqshiftsu:
18065 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
18066 break;
18067 llvm_unreachable("invalid shift count for vqshlu intrinsic");
18068
18069 case Intrinsic::arm_neon_vrshiftn:
18070 case Intrinsic::arm_neon_vqshiftns:
18071 case Intrinsic::arm_neon_vqshiftnu:
18072 case Intrinsic::arm_neon_vqshiftnsu:
18073 case Intrinsic::arm_neon_vqrshiftns:
18074 case Intrinsic::arm_neon_vqrshiftnu:
18075 case Intrinsic::arm_neon_vqrshiftnsu:
18076 // Narrowing shifts require an immediate right shift.
18077 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
18078 break;
18079 llvm_unreachable("invalid shift count for narrowing vector shift "
18080 "intrinsic");
18081
18082 default:
18083 llvm_unreachable("unhandled vector shift");
18084 }
18085
18086 switch (IntNo) {
18087 case Intrinsic::arm_neon_vshifts:
18088 case Intrinsic::arm_neon_vshiftu:
18089 // Opcode already set above.
18090 break;
18091 case Intrinsic::arm_neon_vrshifts:
18092 VShiftOpc = ARMISD::VRSHRsIMM;
18093 break;
18094 case Intrinsic::arm_neon_vrshiftu:
18095 VShiftOpc = ARMISD::VRSHRuIMM;
18096 break;
18097 case Intrinsic::arm_neon_vrshiftn:
18098 VShiftOpc = ARMISD::VRSHRNIMM;
18099 break;
18100 case Intrinsic::arm_neon_vqshifts:
18101 VShiftOpc = ARMISD::VQSHLsIMM;
18102 break;
18103 case Intrinsic::arm_neon_vqshiftu:
18104 VShiftOpc = ARMISD::VQSHLuIMM;
18105 break;
18106 case Intrinsic::arm_neon_vqshiftsu:
18107 VShiftOpc = ARMISD::VQSHLsuIMM;
18108 break;
18109 case Intrinsic::arm_neon_vqshiftns:
18110 VShiftOpc = ARMISD::VQSHRNsIMM;
18111 break;
18112 case Intrinsic::arm_neon_vqshiftnu:
18113 VShiftOpc = ARMISD::VQSHRNuIMM;
18114 break;
18115 case Intrinsic::arm_neon_vqshiftnsu:
18116 VShiftOpc = ARMISD::VQSHRNsuIMM;
18117 break;
18118 case Intrinsic::arm_neon_vqrshiftns:
18119 VShiftOpc = ARMISD::VQRSHRNsIMM;
18120 break;
18121 case Intrinsic::arm_neon_vqrshiftnu:
18122 VShiftOpc = ARMISD::VQRSHRNuIMM;
18123 break;
18124 case Intrinsic::arm_neon_vqrshiftnsu:
18125 VShiftOpc = ARMISD::VQRSHRNsuIMM;
18126 break;
18127 }
18128
18129 SDLoc dl(N);
18130 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
18131 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
18132 }
18133
18134 case Intrinsic::arm_neon_vshiftins: {
18135 EVT VT = N->getOperand(1).getValueType();
18136 int64_t Cnt;
18137 unsigned VShiftOpc = 0;
18138
18139 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
18140 VShiftOpc = ARMISD::VSLIIMM;
18141 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
18142 VShiftOpc = ARMISD::VSRIIMM;
18143 else {
18144 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
18145 }
18146
18147 SDLoc dl(N);
18148 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
18149 N->getOperand(1), N->getOperand(2),
18150 DAG.getConstant(Cnt, dl, MVT::i32));
18151 }
18152
18153 case Intrinsic::arm_neon_vqrshifts:
18154 case Intrinsic::arm_neon_vqrshiftu:
18155 // No immediate versions of these to check for.
18156 break;
18157
18158 case Intrinsic::arm_neon_vbsl: {
18159 SDLoc dl(N);
18160 return DAG.getNode(ARMISD::VBSP, dl, N->getValueType(0), N->getOperand(1),
18161 N->getOperand(2), N->getOperand(3));
18162 }
18163 case Intrinsic::arm_mve_vqdmlah:
18164 case Intrinsic::arm_mve_vqdmlash:
18165 case Intrinsic::arm_mve_vqrdmlah:
18166 case Intrinsic::arm_mve_vqrdmlash:
18167 case Intrinsic::arm_mve_vmla_n_predicated:
18168 case Intrinsic::arm_mve_vmlas_n_predicated:
18169 case Intrinsic::arm_mve_vqdmlah_predicated:
18170 case Intrinsic::arm_mve_vqdmlash_predicated:
18171 case Intrinsic::arm_mve_vqrdmlah_predicated:
18172 case Intrinsic::arm_mve_vqrdmlash_predicated: {
18173 // These intrinsics all take an i32 scalar operand which is narrowed to the
18174 // size of a single lane of the vector type they return. So we don't need
18175 // any bits of that operand above that point, which allows us to eliminate
18176 // uxth/sxth.
18177 unsigned BitWidth = N->getValueType(0).getScalarSizeInBits();
18178 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
18179 if (SimplifyDemandedBits(N->getOperand(3), DemandedMask, DCI))
18180 return SDValue();
18181 break;
18182 }
18183
18184 case Intrinsic::arm_mve_minv:
18185 case Intrinsic::arm_mve_maxv:
18186 case Intrinsic::arm_mve_minav:
18187 case Intrinsic::arm_mve_maxav:
18188 case Intrinsic::arm_mve_minv_predicated:
18189 case Intrinsic::arm_mve_maxv_predicated:
18190 case Intrinsic::arm_mve_minav_predicated:
18191 case Intrinsic::arm_mve_maxav_predicated: {
18192 // These intrinsics all take an i32 scalar operand which is narrowed to the
18193 // size of a single lane of the vector type they take as the other input.
18194 unsigned BitWidth = N->getOperand(2)->getValueType(0).getScalarSizeInBits();
18195 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
18196 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
18197 return SDValue();
18198 break;
18199 }
18200
18201 case Intrinsic::arm_mve_addv: {
18202 // Turn this intrinsic straight into the appropriate ARMISD::VADDV node,
18203 // which allow PerformADDVecReduce to turn it into VADDLV when possible.
18204 bool Unsigned = N->getConstantOperandVal(2);
18205 unsigned Opc = Unsigned ? ARMISD::VADDVu : ARMISD::VADDVs;
18206 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), N->getOperand(1));
18207 }
18208
18209 case Intrinsic::arm_mve_addlv:
18210 case Intrinsic::arm_mve_addlv_predicated: {
18211 // Same for these, but ARMISD::VADDLV has to be followed by a BUILD_PAIR
18212 // which recombines the two outputs into an i64
18213 bool Unsigned = N->getConstantOperandVal(2);
18214 unsigned Opc = IntNo == Intrinsic::arm_mve_addlv ?
18215 (Unsigned ? ARMISD::VADDLVu : ARMISD::VADDLVs) :
18216 (Unsigned ? ARMISD::VADDLVpu : ARMISD::VADDLVps);
18217
18219 for (unsigned i = 1, e = N->getNumOperands(); i < e; i++)
18220 if (i != 2) // skip the unsigned flag
18221 Ops.push_back(N->getOperand(i));
18222
18223 SDLoc dl(N);
18224 SDValue val = DAG.getNode(Opc, dl, {MVT::i32, MVT::i32}, Ops);
18225 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, val.getValue(0),
18226 val.getValue(1));
18227 }
18228 }
18229
18230 return SDValue();
18231}
18232
18234 EVT VT = Y.getValueType();
18235 if (!VT.isVector())
18236 return hasAndNotCompare(Y);
18237 if (Subtarget->hasMVEIntegerOps())
18238 return VT.is128BitVector();
18239 if (Subtarget->hasNEON())
18240 return VT.is64BitVector() || VT.is128BitVector();
18241 return false;
18242}
18243
18244/// PerformShiftCombine - Checks for immediate versions of vector shifts and
18245/// lowers them. As with the vector shift intrinsics, this is done during DAG
18246/// combining instead of DAG legalizing because the build_vectors for 64-bit
18247/// vector element shift counts are generally not legal, and it is hard to see
18248/// their values after they get legalized to loads from a constant pool.
18251 const ARMSubtarget *ST) {
18252 SelectionDAG &DAG = DCI.DAG;
18253 EVT VT = N->getValueType(0);
18254
18255 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
18256 N->getOperand(0)->getOpcode() == ISD::AND &&
18257 N->getOperand(0)->hasOneUse()) {
18258 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18259 return SDValue();
18260 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
18261 // usually show up because instcombine prefers to canonicalize it to
18262 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
18263 // out of GEP lowering in some cases.
18264 SDValue N0 = N->getOperand(0);
18265 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
18266 if (!ShiftAmtNode)
18267 return SDValue();
18268 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
18269 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
18270 if (!AndMaskNode)
18271 return SDValue();
18272 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
18273 // Don't transform uxtb/uxth.
18274 if (AndMask == 255 || AndMask == 65535)
18275 return SDValue();
18276 if (isMask_32(AndMask)) {
18277 uint32_t MaskedBits = llvm::countl_zero(AndMask);
18278 if (MaskedBits > ShiftAmt) {
18279 SDLoc DL(N);
18280 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
18281 DAG.getConstant(MaskedBits, DL, MVT::i32));
18282 return DAG.getNode(
18283 ISD::SRL, DL, MVT::i32, SHL,
18284 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
18285 }
18286 }
18287 }
18288
18289 // Nothing to be done for scalar shifts.
18291 if (!VT.isVector() || !TLI.isTypeLegal(VT))
18292 return SDValue();
18293 if (ST->hasMVEIntegerOps())
18294 return SDValue();
18295
18296 int64_t Cnt;
18297
18298 switch (N->getOpcode()) {
18299 default: llvm_unreachable("unexpected shift opcode");
18300
18301 case ISD::SHL:
18302 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
18303 SDLoc dl(N);
18304 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
18305 DAG.getConstant(Cnt, dl, MVT::i32));
18306 }
18307 break;
18308
18309 case ISD::SRA:
18310 case ISD::SRL:
18311 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
18312 unsigned VShiftOpc =
18313 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
18314 SDLoc dl(N);
18315 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
18316 DAG.getConstant(Cnt, dl, MVT::i32));
18317 }
18318 }
18319 return SDValue();
18320}
18321
18322// Look for a sign/zero/fpextend extend of a larger than legal load. This can be
18323// split into multiple extending loads, which are simpler to deal with than an
18324// arbitrary extend. For fp extends we use an integer extending load and a VCVTL
18325// to convert the type to an f32.
18327 SDValue N0 = N->getOperand(0);
18328 if (N0.getOpcode() != ISD::LOAD)
18329 return SDValue();
18331 if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() ||
18332 LD->getExtensionType() != ISD::NON_EXTLOAD)
18333 return SDValue();
18334 EVT FromVT = LD->getValueType(0);
18335 EVT ToVT = N->getValueType(0);
18336 if (!ToVT.isVector())
18337 return SDValue();
18339 EVT ToEltVT = ToVT.getVectorElementType();
18340 EVT FromEltVT = FromVT.getVectorElementType();
18341
18342 unsigned NumElements = 0;
18343 if (ToEltVT == MVT::i32 && FromEltVT == MVT::i8)
18344 NumElements = 4;
18345 if (ToEltVT == MVT::f32 && FromEltVT == MVT::f16)
18346 NumElements = 4;
18347 if (NumElements == 0 ||
18348 (FromEltVT != MVT::f16 && FromVT.getVectorNumElements() == NumElements) ||
18349 FromVT.getVectorNumElements() % NumElements != 0 ||
18350 !isPowerOf2_32(NumElements))
18351 return SDValue();
18352
18353 LLVMContext &C = *DAG.getContext();
18354 SDLoc DL(LD);
18355 // Details about the old load
18356 SDValue Ch = LD->getChain();
18357 SDValue BasePtr = LD->getBasePtr();
18358 Align Alignment = LD->getBaseAlign();
18359 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
18360 AAMDNodes AAInfo = LD->getAAInfo();
18361
18362 ISD::LoadExtType NewExtType =
18363 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
18364 SDValue Offset = DAG.getPOISON(BasePtr.getValueType());
18365 EVT NewFromVT = EVT::getVectorVT(
18366 C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements);
18367 EVT NewToVT = EVT::getVectorVT(
18368 C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements);
18369
18372 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
18373 unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
18374 SDValue NewPtr =
18375 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(NewOffset));
18376
18377 SDValue NewLoad =
18378 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
18379 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
18380 Alignment, MMOFlags, AAInfo);
18381 Loads.push_back(NewLoad);
18382 Chains.push_back(SDValue(NewLoad.getNode(), 1));
18383 }
18384
18385 // Float truncs need to extended with VCVTB's into their floating point types.
18386 if (FromEltVT == MVT::f16) {
18388
18389 for (unsigned i = 0; i < Loads.size(); i++) {
18390 SDValue LoadBC =
18391 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v8f16, Loads[i]);
18392 SDValue FPExt = DAG.getNode(ARMISD::VCVTL, DL, MVT::v4f32, LoadBC,
18393 DAG.getConstant(0, DL, MVT::i32));
18394 Extends.push_back(FPExt);
18395 }
18396
18397 Loads = Extends;
18398 }
18399
18400 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
18401 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
18402 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Loads);
18403}
18404
18405/// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
18406/// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
18408 const ARMSubtarget *ST) {
18409 SDValue N0 = N->getOperand(0);
18410 EVT VT = N->getValueType(0);
18411 SDLoc DL(N);
18412
18413 // Check for sign- and zero-extensions of vector extract operations of 8- and
18414 // 16-bit vector elements. NEON and MVE support these directly. They are
18415 // handled during DAG combining because type legalization will promote them
18416 // to 32-bit types and it is messy to recognize the operations after that.
18417 if ((ST->hasNEON() || ST->hasMVEIntegerOps()) &&
18419 SDValue Vec = N0.getOperand(0);
18420 SDValue Lane = N0.getOperand(1);
18421 EVT EltVT = N0.getValueType();
18423
18424 if (VT == MVT::i32 &&
18425 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
18426 TLI.isTypeLegal(Vec.getValueType()) &&
18427 isa<ConstantSDNode>(Lane)) {
18428
18429 unsigned Opc = 0;
18430 switch (N->getOpcode()) {
18431 default: llvm_unreachable("unexpected opcode");
18432 case ISD::SIGN_EXTEND:
18433 Opc = ARMISD::VGETLANEs;
18434 break;
18435 case ISD::ZERO_EXTEND:
18436 case ISD::ANY_EXTEND:
18437 Opc = ARMISD::VGETLANEu;
18438 break;
18439 }
18440 return DAG.getNode(Opc, DL, VT, Vec, Lane);
18441 }
18442 }
18443
18444 if (ST->hasMVEIntegerOps())
18445 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
18446 return NewLoad;
18447
18448 // Combine sext(buildvector(..)) to buildvector(sext(..)) to help avoid
18449 // difficult to lower i1 buildvector.
18450 if (ST->hasMVEIntegerOps() && N0.getValueType().getScalarSizeInBits() == 1 &&
18451 N0.getOpcode() == ISD::BUILD_VECTOR && VT.getScalarSizeInBits() <= 32) {
18453 for (unsigned I = 0; I < N0.getNumOperands(); I++) {
18454 SDValue InReg = N0.getOperand(I);
18455 if (N->getOpcode() == ISD::ZERO_EXTEND)
18456 InReg = DAG.getNode(ISD::AND, DL, InReg.getValueType(), InReg,
18457 DAG.getConstant(1, DL, InReg.getValueType()));
18458 else if (N->getOpcode() == ISD::SIGN_EXTEND)
18459 InReg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, InReg.getValueType(),
18460 InReg, DAG.getValueType(MVT::i1));
18461 SDValue Ext = DAG.getNode(N->getOpcode(), DL, MVT::i32, InReg);
18462 Ops.push_back(Ext);
18463 }
18464 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
18465 }
18466
18467 return SDValue();
18468}
18469
18471 const ARMSubtarget *ST) {
18472 if (ST->hasMVEFloatOps())
18473 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
18474 return NewLoad;
18475
18476 return SDValue();
18477}
18478
18479// Lower smin(smax(x, C1), C2) to ssat or usat, if they have saturating
18480// constant bounds.
18482 const ARMSubtarget *Subtarget) {
18483 if ((Subtarget->isThumb() || !Subtarget->hasV6Ops()) &&
18484 !Subtarget->isThumb2())
18485 return SDValue();
18486
18487 EVT VT = Op.getValueType();
18488 SDValue Op0 = Op.getOperand(0);
18489
18490 if (VT != MVT::i32 ||
18491 (Op0.getOpcode() != ISD::SMIN && Op0.getOpcode() != ISD::SMAX) ||
18492 !isa<ConstantSDNode>(Op.getOperand(1)) ||
18494 return SDValue();
18495
18496 SDValue Min = Op;
18497 SDValue Max = Op0;
18498 SDValue Input = Op0.getOperand(0);
18499 if (Min.getOpcode() == ISD::SMAX)
18500 std::swap(Min, Max);
18501
18502 if (Min.getOpcode() != ISD::SMIN || Max.getOpcode() != ISD::SMAX)
18503 return SDValue();
18504
18505 APInt MinC = Min.getConstantOperandAPInt(1);
18506 APInt MaxC = Max.getConstantOperandAPInt(1);
18507 if (MaxC.sgt(MinC))
18508 return SDValue();
18509
18510 SDLoc DL(Op);
18511
18512 // A clamp whose bounds are already a saturation range maps to a single
18513 // SSAT / USAT.
18514 if ((MinC + 1).isPowerOf2()) {
18515 if (MinC == ~MaxC)
18516 return DAG.getNode(ARMISD::SSAT, DL, VT, Input,
18517 DAG.getConstant(MinC.countr_one(), DL, VT));
18518 if (MaxC == 0)
18519 return DAG.getNode(ARMISD::USAT, DL, VT, Input,
18520 DAG.getConstant(MinC.countr_one(), DL, VT));
18521 }
18522
18523 // For power-of-two clamp widths, convert the range to be zero-centered,
18524 // apply SSAT, and convert the result back.
18525 //
18526 // Width = Hi - Lo + 1
18527 // Center = Lo + Width / 2
18528 // Result = ssat(X - Center) + Center
18529 //
18530 // The idea is to shift the input so that the clamp range is centered
18531 // around zero, apply ssat, and then shift the result back.
18532 //
18533 // For example clamp(X, -118, 137) -> Width = 256, Center = 10, so it becomes
18534 // ssat(X - 10, 8) + 10
18535
18536 APInt Width = MinC - MaxC + 1;
18537 if (!Width.isPowerOf2() || Width.isOne())
18538 return SDValue();
18539 unsigned SatBit = Width.logBase2() - 1; // ssat to SatBit + 1 signed bits
18540 APInt Center = MaxC + Width.lshr(1);
18541
18542 // The rewrite is only valid when X - Center does not overflow;
18543 SDValue NegC = DAG.getConstant(-Center, DL, VT);
18545 return SDValue();
18546
18547 SDValue Shifted = DAG.getNode(ISD::ADD, DL, VT, Input, NegC);
18548 SDValue Sat = DAG.getNode(ARMISD::SSAT, DL, VT, Shifted,
18549 DAG.getConstant(SatBit, DL, VT));
18550 return DAG.getNode(ISD::ADD, DL, VT, Sat, DAG.getConstant(Center, DL, VT));
18551}
18552
18553/// PerformMinMaxCombine - Target-specific DAG combining for creating truncating
18554/// saturates.
18556 const ARMSubtarget *ST) {
18557 EVT VT = N->getValueType(0);
18558 SDValue N0 = N->getOperand(0);
18559
18560 if (VT == MVT::i32)
18561 return PerformMinMaxToSatCombine(SDValue(N, 0), DAG, ST);
18562
18563 if (!ST->hasMVEIntegerOps())
18564 return SDValue();
18565
18566 if (SDValue V = PerformVQDMULHCombine(N, DAG))
18567 return V;
18568
18569 if (VT != MVT::v4i32 && VT != MVT::v8i16)
18570 return SDValue();
18571
18572 auto IsSignedSaturate = [&](SDNode *Min, SDNode *Max) {
18573 // Check one is a smin and the other is a smax
18574 if (Min->getOpcode() != ISD::SMIN)
18575 std::swap(Min, Max);
18576 if (Min->getOpcode() != ISD::SMIN || Max->getOpcode() != ISD::SMAX)
18577 return false;
18578
18579 APInt SaturateC;
18580 if (VT == MVT::v4i32)
18581 SaturateC = APInt(32, (1 << 15) - 1, true);
18582 else //if (VT == MVT::v8i16)
18583 SaturateC = APInt(16, (1 << 7) - 1, true);
18584
18585 APInt MinC, MaxC;
18586 if (!ISD::isConstantSplatVector(Min->getOperand(1), MinC) ||
18587 MinC != SaturateC)
18588 return false;
18589 if (!ISD::isConstantSplatVector(Max->getOperand(1), MaxC) ||
18590 MaxC != ~SaturateC)
18591 return false;
18592 return true;
18593 };
18594
18595 if (IsSignedSaturate(N, N0.getNode())) {
18596 SDLoc DL(N);
18597 MVT ExtVT, HalfVT;
18598 if (VT == MVT::v4i32) {
18599 HalfVT = MVT::v8i16;
18600 ExtVT = MVT::v4i16;
18601 } else { // if (VT == MVT::v8i16)
18602 HalfVT = MVT::v16i8;
18603 ExtVT = MVT::v8i8;
18604 }
18605
18606 // Create a VQMOVNB with undef top lanes, then signed extended into the top
18607 // half. That extend will hopefully be removed if only the bottom bits are
18608 // demanded (though a truncating store, for example).
18609 SDValue VQMOVN =
18610 DAG.getNode(ARMISD::VQMOVNs, DL, HalfVT, DAG.getUNDEF(HalfVT),
18611 N0->getOperand(0), DAG.getConstant(0, DL, MVT::i32));
18612 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
18613 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Bitcast,
18614 DAG.getValueType(ExtVT));
18615 }
18616
18617 auto IsUnsignedSaturate = [&](SDNode *Min) {
18618 // For unsigned, we just need to check for <= 0xffff
18619 if (Min->getOpcode() != ISD::UMIN)
18620 return false;
18621
18622 APInt SaturateC;
18623 if (VT == MVT::v4i32)
18624 SaturateC = APInt(32, (1 << 16) - 1, true);
18625 else //if (VT == MVT::v8i16)
18626 SaturateC = APInt(16, (1 << 8) - 1, true);
18627
18628 APInt MinC;
18629 if (!ISD::isConstantSplatVector(Min->getOperand(1), MinC) ||
18630 MinC != SaturateC)
18631 return false;
18632 return true;
18633 };
18634
18635 if (IsUnsignedSaturate(N)) {
18636 SDLoc DL(N);
18637 MVT HalfVT;
18638 unsigned ExtConst;
18639 if (VT == MVT::v4i32) {
18640 HalfVT = MVT::v8i16;
18641 ExtConst = 0x0000FFFF;
18642 } else { //if (VT == MVT::v8i16)
18643 HalfVT = MVT::v16i8;
18644 ExtConst = 0x00FF;
18645 }
18646
18647 // Create a VQMOVNB with undef top lanes, then ZExt into the top half with
18648 // an AND. That extend will hopefully be removed if only the bottom bits are
18649 // demanded (though a truncating store, for example).
18650 SDValue VQMOVN =
18651 DAG.getNode(ARMISD::VQMOVNu, DL, HalfVT, DAG.getUNDEF(HalfVT), N0,
18652 DAG.getConstant(0, DL, MVT::i32));
18653 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
18654 return DAG.getNode(ISD::AND, DL, VT, Bitcast,
18655 DAG.getConstant(ExtConst, DL, VT));
18656 }
18657
18658 return SDValue();
18659}
18660
18663 if (!C)
18664 return nullptr;
18665 const APInt *CV = &C->getAPIntValue();
18666 return CV->isPowerOf2() ? CV : nullptr;
18667}
18668
18670 // If we have a CMOV, OR and AND combination such as:
18671 // if (x & CN)
18672 // y |= CM;
18673 //
18674 // And:
18675 // * CN is a single bit;
18676 // * All bits covered by CM are known zero in y
18677 //
18678 // Then we can convert this into a sequence of BFI instructions. This will
18679 // always be a win if CM is a single bit, will always be no worse than the
18680 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
18681 // three bits (due to the extra IT instruction).
18682
18683 SDValue Op0 = CMOV->getOperand(0);
18684 SDValue Op1 = CMOV->getOperand(1);
18685 auto CC = CMOV->getConstantOperandAPInt(2).getLimitedValue();
18686 SDValue CmpZ = CMOV->getOperand(3);
18687
18688 // The compare must be against zero.
18689 if (!isNullConstant(CmpZ->getOperand(1)))
18690 return SDValue();
18691
18692 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
18693 SDValue And = CmpZ->getOperand(0);
18694 if (And->getOpcode() != ISD::AND)
18695 return SDValue();
18696 const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
18697 if (!AndC)
18698 return SDValue();
18699 SDValue X = And->getOperand(0);
18700
18701 if (CC == ARMCC::EQ) {
18702 // We're performing an "equal to zero" compare. Swap the operands so we
18703 // canonicalize on a "not equal to zero" compare.
18704 std::swap(Op0, Op1);
18705 } else {
18706 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
18707 }
18708
18709 if (Op1->getOpcode() != ISD::OR)
18710 return SDValue();
18711
18713 if (!OrC)
18714 return SDValue();
18715 SDValue Y = Op1->getOperand(0);
18716
18717 if (Op0 != Y)
18718 return SDValue();
18719
18720 // Now, is it profitable to continue?
18721 APInt OrCI = OrC->getAPIntValue();
18722 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
18723 if (OrCI.popcount() > Heuristic)
18724 return SDValue();
18725
18726 // Lastly, can we determine that the bits defined by OrCI
18727 // are zero in Y?
18729 if ((OrCI & Known.Zero) != OrCI)
18730 return SDValue();
18731
18732 // OK, we can do the combine.
18733 SDValue V = Y;
18734 SDLoc dl(X);
18735 EVT VT = X.getValueType();
18736 unsigned BitInX = AndC->logBase2();
18737
18738 if (BitInX != 0) {
18739 // We must shift X first.
18740 X = DAG.getNode(ISD::SRL, dl, VT, X,
18741 DAG.getConstant(BitInX, dl, VT));
18742 }
18743
18744 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
18745 BitInY < NumActiveBits; ++BitInY) {
18746 if (OrCI[BitInY] == 0)
18747 continue;
18748 APInt Mask(VT.getSizeInBits(), 0);
18749 Mask.setBit(BitInY);
18750 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
18751 // Confusingly, the operand is an *inverted* mask.
18752 DAG.getConstant(~Mask, dl, VT));
18753 }
18754
18755 return V;
18756}
18757
18758// Given N, the value controlling the conditional branch, search for the loop
18759// intrinsic, returning it, along with how the value is used. We need to handle
18760// patterns such as the following:
18761// (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
18762// (brcond (setcc (loop.decrement), 0, eq), exit)
18763// (brcond (setcc (loop.decrement), 0, ne), header)
18765 bool &Negate) {
18766 switch (N->getOpcode()) {
18767 default:
18768 break;
18769 case ISD::XOR: {
18770 if (!isa<ConstantSDNode>(N.getOperand(1)))
18771 return SDValue();
18772 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
18773 return SDValue();
18774 Negate = !Negate;
18775 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
18776 }
18777 case ISD::SETCC: {
18778 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
18779 if (!Const)
18780 return SDValue();
18781 if (Const->isZero())
18782 Imm = 0;
18783 else if (Const->isOne())
18784 Imm = 1;
18785 else
18786 return SDValue();
18787 CC = N.getOperandCondCode(2);
18788 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
18789 }
18791 unsigned IntOp = N.getConstantOperandVal(1);
18792 if (IntOp != Intrinsic::test_start_loop_iterations &&
18793 IntOp != Intrinsic::loop_decrement_reg)
18794 return SDValue();
18795 return N;
18796 }
18797 }
18798 return SDValue();
18799}
18800
18803 const ARMSubtarget *ST) {
18804
18805 // The hwloop intrinsics that we're interested are used for control-flow,
18806 // either for entering or exiting the loop:
18807 // - test.start.loop.iterations will test whether its operand is zero. If it
18808 // is zero, the proceeding branch should not enter the loop.
18809 // - loop.decrement.reg also tests whether its operand is zero. If it is
18810 // zero, the proceeding branch should not branch back to the beginning of
18811 // the loop.
18812 // So here, we need to check that how the brcond is using the result of each
18813 // of the intrinsics to ensure that we're branching to the right place at the
18814 // right time.
18815
18817 SDValue Cond;
18818 int Imm = 1;
18819 bool Negate = false;
18820 SDValue Chain = N->getOperand(0);
18821 SDValue Dest;
18822
18823 if (N->getOpcode() == ISD::BRCOND) {
18824 CC = ISD::SETEQ;
18825 Cond = N->getOperand(1);
18826 Dest = N->getOperand(2);
18827 } else {
18828 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
18829 CC = N->getOperandCondCode(1);
18830 Cond = N->getOperand(2);
18831 Dest = N->getOperand(4);
18832 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
18833 if (!Const->isOne() && !Const->isZero())
18834 return SDValue();
18835 Imm = Const->getZExtValue();
18836 } else
18837 return SDValue();
18838 }
18839
18841 if (!Int)
18842 return SDValue();
18843
18844 if (Negate)
18845 CC = ISD::getSetCCInverse(CC, /* Integer inverse */ MVT::i32);
18846
18847 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
18848 return (CC == ISD::SETEQ && Imm == 0) ||
18849 (CC == ISD::SETNE && Imm == 1) ||
18850 (CC == ISD::SETLT && Imm == 1) ||
18851 (CC == ISD::SETULT && Imm == 1);
18852 };
18853
18854 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
18855 return (CC == ISD::SETEQ && Imm == 1) ||
18856 (CC == ISD::SETNE && Imm == 0) ||
18857 (CC == ISD::SETGT && Imm == 0) ||
18858 (CC == ISD::SETUGT && Imm == 0) ||
18859 (CC == ISD::SETGE && Imm == 1) ||
18860 (CC == ISD::SETUGE && Imm == 1);
18861 };
18862
18863 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
18864 "unsupported condition");
18865
18866 SDLoc dl(Int);
18867 SelectionDAG &DAG = DCI.DAG;
18868 SDValue Elements = Int.getOperand(2);
18869 unsigned IntOp = Int->getConstantOperandVal(1);
18870 assert((N->hasOneUse() && N->user_begin()->getOpcode() == ISD::BR) &&
18871 "expected single br user");
18872 SDNode *Br = *N->user_begin();
18873 SDValue OtherTarget = Br->getOperand(1);
18874
18875 // Update the unconditional branch to branch to the given Dest.
18876 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
18877 SDValue NewBrOps[] = { Br->getOperand(0), Dest };
18878 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
18879 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
18880 };
18881
18882 if (IntOp == Intrinsic::test_start_loop_iterations) {
18883 SDValue Res;
18884 SDValue Setup = DAG.getNode(ARMISD::WLSSETUP, dl, MVT::i32, Elements);
18885 // We expect this 'instruction' to branch when the counter is zero.
18886 if (IsTrueIfZero(CC, Imm)) {
18887 SDValue Ops[] = {Chain, Setup, Dest};
18888 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
18889 } else {
18890 // The logic is the reverse of what we need for WLS, so find the other
18891 // basic block target: the target of the proceeding br.
18892 UpdateUncondBr(Br, Dest, DAG);
18893
18894 SDValue Ops[] = {Chain, Setup, OtherTarget};
18895 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
18896 }
18897 // Update LR count to the new value
18898 DAG.ReplaceAllUsesOfValueWith(Int.getValue(0), Setup);
18899 // Update chain
18900 DAG.ReplaceAllUsesOfValueWith(Int.getValue(2), Int.getOperand(0));
18901 return Res;
18902 } else {
18903 SDValue Size =
18904 DAG.getTargetConstant(Int.getConstantOperandVal(3), dl, MVT::i32);
18905 SDValue Args[] = { Int.getOperand(0), Elements, Size, };
18906 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
18907 DAG.getVTList(MVT::i32, MVT::Other), Args);
18908 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
18909
18910 // We expect this instruction to branch when the count is not zero.
18911 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
18912
18913 // Update the unconditional branch to target the loop preheader if we've
18914 // found the condition has been reversed.
18915 if (Target == OtherTarget)
18916 UpdateUncondBr(Br, Dest, DAG);
18917
18918 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18919 SDValue(LoopDec.getNode(), 1), Chain);
18920
18921 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
18922 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
18923 }
18924 return SDValue();
18925}
18926
18927/// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
18928SDValue
18930 SDValue Cmp = N->getOperand(3);
18931 if (Cmp.getOpcode() != ARMISD::CMPZ)
18932 // Only looking at NE cases.
18933 return SDValue();
18934
18935 SDLoc dl(N);
18936 SDValue LHS = Cmp.getOperand(0);
18937 SDValue RHS = Cmp.getOperand(1);
18938 SDValue Chain = N->getOperand(0);
18939 SDValue BB = N->getOperand(1);
18940 SDValue ARMcc = N->getOperand(2);
18942
18943 // (brcond Chain BB ne (cmpz (and (cmov 0 1 CC Flags) 1) 0))
18944 // -> (brcond Chain BB CC Flags)
18945 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
18946 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
18947 LHS->getOperand(0)->hasOneUse() &&
18948 isNullConstant(LHS->getOperand(0)->getOperand(0)) &&
18949 isOneConstant(LHS->getOperand(0)->getOperand(1)) &&
18950 isOneConstant(LHS->getOperand(1)) && isNullConstant(RHS)) {
18951 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, BB,
18952 LHS->getOperand(0)->getOperand(2),
18953 LHS->getOperand(0)->getOperand(3));
18954 }
18955
18956 return SDValue();
18957}
18958
18959/// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
18960SDValue
18962 SDLoc dl(N);
18963 EVT VT = N->getValueType(0);
18964 SDValue FalseVal = N->getOperand(0);
18965 SDValue TrueVal = N->getOperand(1);
18966 SDValue ARMcc = N->getOperand(2);
18967 SDValue Cmp = N->getOperand(3);
18968
18969 // Try to form CSINV etc.
18970 unsigned Opcode;
18971 bool InvertCond;
18972 if (SDValue CSetOp =
18973 matchCSET(Opcode, InvertCond, TrueVal, FalseVal, Subtarget)) {
18974 if (InvertCond) {
18975 ARMCC::CondCodes CondCode =
18976 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
18977 CondCode = ARMCC::getOppositeCondition(CondCode);
18978 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
18979 }
18980 return DAG.getNode(Opcode, dl, VT, CSetOp, CSetOp, ARMcc, Cmp);
18981 }
18982
18983 if (Cmp.getOpcode() != ARMISD::CMPZ)
18984 // Only looking at EQ and NE cases.
18985 return SDValue();
18986
18987 SDValue LHS = Cmp.getOperand(0);
18988 SDValue RHS = Cmp.getOperand(1);
18990
18991 // BFI is only available on V6T2+.
18992 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
18994 if (R)
18995 return R;
18996 }
18997
18998 // Simplify
18999 // mov r1, r0
19000 // cmp r1, x
19001 // mov r0, y
19002 // moveq r0, x
19003 // to
19004 // cmp r0, x
19005 // movne r0, y
19006 //
19007 // mov r1, r0
19008 // cmp r1, x
19009 // mov r0, x
19010 // movne r0, y
19011 // to
19012 // cmp r0, x
19013 // movne r0, y
19014 /// FIXME: Turn this into a target neutral optimization?
19015 SDValue Res;
19016 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
19017 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, Cmp);
19018 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
19019 SDValue ARMcc;
19020 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
19021 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, NewCmp);
19022 }
19023
19024 // (cmov F T ne (cmpz (cmov 0 1 CC Flags) 0))
19025 // -> (cmov F T CC Flags)
19026 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse() &&
19027 isNullConstant(LHS->getOperand(0)) && isOneConstant(LHS->getOperand(1)) &&
19028 isNullConstant(RHS)) {
19029 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
19030 LHS->getOperand(2), LHS->getOperand(3));
19031 }
19032
19033 if (!VT.isInteger())
19034 return SDValue();
19035
19036 // Fold away an unnecessary CMPZ/CMOV
19037 // CMOV A, B, C1, (CMPZ (CMOV 1, 0, C2, D), 0) ->
19038 // if C1==EQ -> CMOV A, B, C2, D
19039 // if C1==NE -> CMOV A, B, NOT(C2), D
19040 if (N->getConstantOperandVal(2) == ARMCC::EQ ||
19041 N->getConstantOperandVal(2) == ARMCC::NE) {
19043 if (SDValue C = IsCMPZCSINC(N->getOperand(3).getNode(), Cond)) {
19044 if (N->getConstantOperandVal(2) == ARMCC::NE)
19046 return DAG.getNode(N->getOpcode(), SDLoc(N), MVT::i32, N->getOperand(0),
19047 N->getOperand(1),
19048 DAG.getConstant(Cond, SDLoc(N), MVT::i32), C);
19049 }
19050 }
19051
19052 // Materialize a boolean comparison for integers so we can avoid branching.
19053 if (isNullConstant(FalseVal)) {
19054 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
19055 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
19056 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
19057 // right 5 bits will make that 32 be 1, otherwise it will be 0.
19058 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
19059 SDValue Value;
19060 if (VT == MVT::i32 && Subtarget->isThumb2() && isNullConstant(RHS) &&
19061 Cmp.hasOneUse())
19062 Value = getShiftedLowMaskZeroTest(LHS, DAG, dl);
19063 if (!Value)
19064 Value = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
19065 Res =
19066 DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Value),
19067 DAG.getConstant(5, dl, MVT::i32));
19068 } else {
19069 // CMOV 0, 1, ==, (CMPZ x, y) ->
19070 // (UADDO_CARRY (SUB x, y), t:0, t:1)
19071 // where t = (USUBO_CARRY 0, (SUB x, y), 0)
19072 //
19073 // The USUBO_CARRY computes 0 - (x - y) and this will give a borrow when
19074 // x != y. In other words, a carry C == 1 when x == y, C == 0
19075 // otherwise.
19076 // The final UADDO_CARRY computes
19077 // x - y + (0 - (x - y)) + C == C
19078 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
19079 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19080 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
19081 // ISD::USUBO_CARRY returns a borrow but we want the carry here
19082 // actually.
19083 SDValue Carry =
19084 DAG.getNode(ISD::SUB, dl, MVT::i32,
19085 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
19086 Res = DAG.getNode(ISD::UADDO_CARRY, dl, VTs, Sub, Neg, Carry);
19087 }
19088 } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
19089 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
19090 // This seems pointless but will allow us to combine it further below.
19091 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBC x, y), z, !=, (SUBC x, y):1
19092 SDValue Sub =
19093 DAG.getNode(ARMISD::SUBC, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
19094 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
19095 Sub.getValue(1));
19096 FalseVal = Sub;
19097 }
19098 } else if (isNullConstant(TrueVal)) {
19099 if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
19100 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
19101 // This seems pointless but will allow us to combine it further below
19102 // Note that we change == for != as this is the dual for the case above.
19103 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBC x, y), z, !=, (SUBC x, y):1
19104 SDValue Sub =
19105 DAG.getNode(ARMISD::SUBC, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
19106 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
19107 DAG.getConstant(ARMCC::NE, dl, MVT::i32),
19108 Sub.getValue(1));
19109 FalseVal = Sub;
19110 }
19111 }
19112
19113 // On Thumb1, the DAG above may be further combined if z is a power of 2
19114 // (z == 2 ^ K).
19115 // CMOV (SUBC x, y), z, !=, (SUBC x, y):1 ->
19116 // t1 = (USUBO (SUB x, y), 1)
19117 // t2 = (USUBO_CARRY (SUB x, y), t1:0, t1:1)
19118 // Result = if K != 0 then (SHL t2:0, K) else t2:0
19119 //
19120 // This also handles the special case of comparing against zero; it's
19121 // essentially, the same pattern, except there's no SUBC:
19122 // CMOV x, z, !=, (CMPZ x, 0) ->
19123 // t1 = (USUBO x, 1)
19124 // t2 = (USUBO_CARRY x, t1:0, t1:1)
19125 // Result = if K != 0 then (SHL t2:0, K) else t2:0
19126 const APInt *TrueConst;
19127 if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
19128 ((FalseVal.getOpcode() == ARMISD::SUBC && FalseVal.getOperand(0) == LHS &&
19129 FalseVal.getOperand(1) == RHS) ||
19130 (FalseVal == LHS && isNullConstant(RHS))) &&
19131 (TrueConst = isPowerOf2Constant(TrueVal))) {
19132 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19133 unsigned ShiftAmount = TrueConst->logBase2();
19134 if (ShiftAmount)
19135 TrueVal = DAG.getConstant(1, dl, VT);
19136 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
19137 Res = DAG.getNode(ISD::USUBO_CARRY, dl, VTs, FalseVal, Subc,
19138 Subc.getValue(1));
19139
19140 if (ShiftAmount)
19141 Res = DAG.getNode(ISD::SHL, dl, VT, Res,
19142 DAG.getConstant(ShiftAmount, dl, MVT::i32));
19143 }
19144
19145 if (Res.getNode()) {
19147 // Capture demanded bits information that would be otherwise lost.
19148 if (Known.Zero == 0xfffffffe)
19149 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
19150 DAG.getValueType(MVT::i1));
19151 else if (Known.Zero == 0xffffff00)
19152 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
19153 DAG.getValueType(MVT::i8));
19154 else if (Known.Zero == 0xffff0000)
19155 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
19156 DAG.getValueType(MVT::i16));
19157 }
19158
19159 return Res;
19160}
19161
19164 const ARMSubtarget *ST) {
19165 SelectionDAG &DAG = DCI.DAG;
19166 SDValue Src = N->getOperand(0);
19167 EVT DstVT = N->getValueType(0);
19168
19169 // Convert v4f32 bitcast (v4i32 vdup (i32)) -> v4f32 vdup (i32) under MVE.
19170 if (ST->hasMVEIntegerOps() && Src.getOpcode() == ARMISD::VDUP) {
19171 EVT SrcVT = Src.getValueType();
19172 if (SrcVT.getScalarSizeInBits() == DstVT.getScalarSizeInBits())
19173 return DAG.getNode(ARMISD::VDUP, SDLoc(N), DstVT, Src.getOperand(0));
19174 }
19175
19176 // We may have a bitcast of something that has already had this bitcast
19177 // combine performed on it, so skip past any VECTOR_REG_CASTs.
19178 if (Src.getOpcode() == ARMISD::VECTOR_REG_CAST &&
19179 Src.getOperand(0).getValueType().getScalarSizeInBits() <=
19180 Src.getValueType().getScalarSizeInBits())
19181 Src = Src.getOperand(0);
19182
19183 // Bitcast from element-wise VMOV or VMVN doesn't need VREV if the VREV that
19184 // would be generated is at least the width of the element type.
19185 EVT SrcVT = Src.getValueType();
19186 if ((Src.getOpcode() == ARMISD::VMOVIMM ||
19187 Src.getOpcode() == ARMISD::VMVNIMM ||
19188 Src.getOpcode() == ARMISD::VMOVFPIMM) &&
19189 SrcVT.getScalarSizeInBits() <= DstVT.getScalarSizeInBits() &&
19190 DAG.getDataLayout().isBigEndian())
19191 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(N), DstVT, Src);
19192
19193 // bitcast(extract(x, n)); bitcast(extract(x, n+1)) -> VMOVRRD x
19194 if (SDValue R = PerformExtractEltToVMOVRRD(N, DCI))
19195 return R;
19196
19197 return SDValue();
19198}
19199
19200// Some combines for the MVETrunc truncations legalizer helper. Also lowers the
19201// node into stack operations after legalizeOps.
19204 SelectionDAG &DAG = DCI.DAG;
19205 EVT VT = N->getValueType(0);
19206 SDLoc DL(N);
19207
19208 // MVETrunc(Undef, Undef) -> Undef
19209 if (all_of(N->ops(), [](SDValue Op) { return Op.isUndef(); }))
19210 return DAG.getUNDEF(VT);
19211
19212 // MVETrunc(MVETrunc a b, MVETrunc c, d) -> MVETrunc
19213 if (N->getNumOperands() == 2 &&
19214 N->getOperand(0).getOpcode() == ARMISD::MVETRUNC &&
19215 N->getOperand(1).getOpcode() == ARMISD::MVETRUNC)
19216 return DAG.getNode(ARMISD::MVETRUNC, DL, VT, N->getOperand(0).getOperand(0),
19217 N->getOperand(0).getOperand(1),
19218 N->getOperand(1).getOperand(0),
19219 N->getOperand(1).getOperand(1));
19220
19221 // MVETrunc(shuffle, shuffle) -> VMOVN
19222 if (N->getNumOperands() == 2 &&
19223 N->getOperand(0).getOpcode() == ISD::VECTOR_SHUFFLE &&
19224 N->getOperand(1).getOpcode() == ISD::VECTOR_SHUFFLE) {
19225 auto *S0 = cast<ShuffleVectorSDNode>(N->getOperand(0).getNode());
19226 auto *S1 = cast<ShuffleVectorSDNode>(N->getOperand(1).getNode());
19227
19228 if (S0->getOperand(0) == S1->getOperand(0) &&
19229 S0->getOperand(1) == S1->getOperand(1)) {
19230 // Construct complete shuffle mask
19231 SmallVector<int, 8> Mask(S0->getMask());
19232 Mask.append(S1->getMask().begin(), S1->getMask().end());
19233
19234 if (isVMOVNTruncMask(Mask, VT, false))
19235 return DAG.getNode(
19236 ARMISD::VMOVN, DL, VT,
19237 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(0)),
19238 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(1)),
19239 DAG.getConstant(1, DL, MVT::i32));
19240 if (isVMOVNTruncMask(Mask, VT, true))
19241 return DAG.getNode(
19242 ARMISD::VMOVN, DL, VT,
19243 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(1)),
19244 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(0)),
19245 DAG.getConstant(1, DL, MVT::i32));
19246 }
19247 }
19248
19249 // For MVETrunc of a buildvector or shuffle, it can be beneficial to lower the
19250 // truncate to a buildvector to allow the generic optimisations to kick in.
19251 if (all_of(N->ops(), [](SDValue Op) {
19252 return Op.getOpcode() == ISD::BUILD_VECTOR ||
19253 Op.getOpcode() == ISD::VECTOR_SHUFFLE ||
19254 (Op.getOpcode() == ISD::BITCAST &&
19255 Op.getOperand(0).getOpcode() == ISD::BUILD_VECTOR);
19256 })) {
19257 SmallVector<SDValue, 8> Extracts;
19258 for (unsigned Op = 0; Op < N->getNumOperands(); Op++) {
19259 SDValue O = N->getOperand(Op);
19260 for (unsigned i = 0; i < O.getValueType().getVectorNumElements(); i++) {
19261 SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, O,
19262 DAG.getConstant(i, DL, MVT::i32));
19263 Extracts.push_back(Ext);
19264 }
19265 }
19266 return DAG.getBuildVector(VT, DL, Extracts);
19267 }
19268
19269 // If we are late in the legalization process and nothing has optimised
19270 // the trunc to anything better, lower it to a stack store and reload,
19271 // performing the truncation whilst keeping the lanes in the correct order:
19272 // VSTRH.32 a, stack; VSTRH.32 b, stack+8; VLDRW.32 stack;
19273 if (!DCI.isAfterLegalizeDAG())
19274 return SDValue();
19275
19276 SDValue StackPtr = DAG.CreateStackTemporary(TypeSize::getFixed(16), Align(4));
19277 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
19278 int NumIns = N->getNumOperands();
19279 assert((NumIns == 2 || NumIns == 4) &&
19280 "Expected 2 or 4 inputs to an MVETrunc");
19281 EVT StoreVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
19282 if (N->getNumOperands() == 4)
19283 StoreVT = StoreVT.getHalfNumVectorElementsVT(*DAG.getContext());
19284
19285 SmallVector<SDValue> Chains;
19286 for (int I = 0; I < NumIns; I++) {
19287 SDValue Ptr = DAG.getNode(
19288 ISD::ADD, DL, StackPtr.getValueType(), StackPtr,
19289 DAG.getConstant(I * 16 / NumIns, DL, StackPtr.getValueType()));
19291 DAG.getMachineFunction(), SPFI, I * 16 / NumIns);
19292 SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), DL, N->getOperand(I),
19293 Ptr, MPI, StoreVT, Align(4));
19294 Chains.push_back(Ch);
19295 }
19296
19297 SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
19298 MachinePointerInfo MPI =
19300 return DAG.getLoad(VT, DL, Chain, StackPtr, MPI, Align(4));
19301}
19302
19303// Take a MVEEXT(load x) and split that into (extload x, extload x+8)
19305 SelectionDAG &DAG) {
19306 SDValue N0 = N->getOperand(0);
19308 if (!LD || !LD->isSimple() || !N0.hasOneUse() || LD->isIndexed())
19309 return SDValue();
19310
19311 EVT FromVT = LD->getMemoryVT();
19312 EVT ToVT = N->getValueType(0);
19313 if (!ToVT.isVector())
19314 return SDValue();
19315 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements() * 2);
19316 EVT ToEltVT = ToVT.getVectorElementType();
19317 EVT FromEltVT = FromVT.getVectorElementType();
19318
19319 unsigned NumElements = 0;
19320 if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8))
19321 NumElements = 4;
19322 if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8)
19323 NumElements = 8;
19324 assert(NumElements != 0);
19325
19326 ISD::LoadExtType NewExtType =
19327 N->getOpcode() == ARMISD::MVESEXT ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
19328 if (LD->getExtensionType() != ISD::NON_EXTLOAD &&
19329 LD->getExtensionType() != ISD::EXTLOAD &&
19330 LD->getExtensionType() != NewExtType)
19331 return SDValue();
19332
19333 LLVMContext &C = *DAG.getContext();
19334 SDLoc DL(LD);
19335 // Details about the old load
19336 SDValue Ch = LD->getChain();
19337 SDValue BasePtr = LD->getBasePtr();
19338 Align Alignment = LD->getBaseAlign();
19339 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
19340 AAMDNodes AAInfo = LD->getAAInfo();
19341
19342 SDValue Offset = DAG.getPOISON(BasePtr.getValueType());
19343 EVT NewFromVT = EVT::getVectorVT(
19344 C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements);
19345 EVT NewToVT = EVT::getVectorVT(
19346 C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements);
19347
19350 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
19351 unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
19352 SDValue NewPtr =
19353 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(NewOffset));
19354
19355 SDValue NewLoad =
19356 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
19357 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
19358 Alignment, MMOFlags, AAInfo);
19359 Loads.push_back(NewLoad);
19360 Chains.push_back(SDValue(NewLoad.getNode(), 1));
19361 }
19362
19363 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
19364 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
19365 return DAG.getMergeValues(Loads, DL);
19366}
19367
19368// Perform combines for MVEEXT. If it has not be optimized to anything better
19369// before lowering, it gets converted to stack store and extloads performing the
19370// extend whilst still keeping the same lane ordering.
19373 SelectionDAG &DAG = DCI.DAG;
19374 EVT VT = N->getValueType(0);
19375 SDLoc DL(N);
19376 assert(N->getNumValues() == 2 && "Expected MVEEXT with 2 elements");
19377 assert((VT == MVT::v4i32 || VT == MVT::v8i16) && "Unexpected MVEEXT type");
19378
19379 EVT ExtVT = N->getOperand(0).getValueType().getHalfNumVectorElementsVT(
19380 *DAG.getContext());
19381 auto Extend = [&](SDValue V) {
19382 SDValue VVT = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, V);
19383 return N->getOpcode() == ARMISD::MVESEXT
19384 ? DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, VVT,
19385 DAG.getValueType(ExtVT))
19386 : DAG.getZeroExtendInReg(VVT, DL, ExtVT);
19387 };
19388
19389 // MVEEXT(VDUP) -> SIGN_EXTEND_INREG(VDUP)
19390 if (N->getOperand(0).getOpcode() == ARMISD::VDUP) {
19391 SDValue Ext = Extend(N->getOperand(0));
19392 return DAG.getMergeValues({Ext, Ext}, DL);
19393 }
19394
19395 // MVEEXT(shuffle) -> SIGN_EXTEND_INREG/ZERO_EXTEND_INREG
19396 if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(N->getOperand(0))) {
19397 ArrayRef<int> Mask = SVN->getMask();
19398 assert(Mask.size() == 2 * VT.getVectorNumElements());
19399 assert(Mask.size() == SVN->getValueType(0).getVectorNumElements());
19400 unsigned Rev = VT == MVT::v4i32 ? ARMISD::VREV32 : ARMISD::VREV16;
19401 SDValue Op0 = SVN->getOperand(0);
19402 SDValue Op1 = SVN->getOperand(1);
19403
19404 auto CheckInregMask = [&](int Start, int Offset) {
19405 for (int Idx = 0, E = VT.getVectorNumElements(); Idx < E; ++Idx)
19406 if (Mask[Start + Idx] >= 0 && Mask[Start + Idx] != Idx * 2 + Offset)
19407 return false;
19408 return true;
19409 };
19410 SDValue V0 = SDValue(N, 0);
19411 SDValue V1 = SDValue(N, 1);
19412 if (CheckInregMask(0, 0))
19413 V0 = Extend(Op0);
19414 else if (CheckInregMask(0, 1))
19415 V0 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op0));
19416 else if (CheckInregMask(0, Mask.size()))
19417 V0 = Extend(Op1);
19418 else if (CheckInregMask(0, Mask.size() + 1))
19419 V0 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op1));
19420
19421 if (CheckInregMask(VT.getVectorNumElements(), Mask.size()))
19422 V1 = Extend(Op1);
19423 else if (CheckInregMask(VT.getVectorNumElements(), Mask.size() + 1))
19424 V1 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op1));
19425 else if (CheckInregMask(VT.getVectorNumElements(), 0))
19426 V1 = Extend(Op0);
19427 else if (CheckInregMask(VT.getVectorNumElements(), 1))
19428 V1 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op0));
19429
19430 if (V0.getNode() != N || V1.getNode() != N)
19431 return DAG.getMergeValues({V0, V1}, DL);
19432 }
19433
19434 // MVEEXT(load) -> extload, extload
19435 if (N->getOperand(0)->getOpcode() == ISD::LOAD)
19437 return L;
19438
19439 if (!DCI.isAfterLegalizeDAG())
19440 return SDValue();
19441
19442 // Lower to a stack store and reload:
19443 // VSTRW.32 a, stack; VLDRH.32 stack; VLDRH.32 stack+8;
19444 SDValue StackPtr = DAG.CreateStackTemporary(TypeSize::getFixed(16), Align(4));
19445 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
19446 int NumOuts = N->getNumValues();
19447 assert((NumOuts == 2 || NumOuts == 4) &&
19448 "Expected 2 or 4 outputs to an MVEEXT");
19449 EVT LoadVT = N->getOperand(0).getValueType().getHalfNumVectorElementsVT(
19450 *DAG.getContext());
19451 if (N->getNumOperands() == 4)
19452 LoadVT = LoadVT.getHalfNumVectorElementsVT(*DAG.getContext());
19453
19454 MachinePointerInfo MPI =
19456 SDValue Chain = DAG.getStore(DAG.getEntryNode(), DL, N->getOperand(0),
19457 StackPtr, MPI, Align(4));
19458
19460 for (int I = 0; I < NumOuts; I++) {
19461 SDValue Ptr = DAG.getNode(
19462 ISD::ADD, DL, StackPtr.getValueType(), StackPtr,
19463 DAG.getConstant(I * 16 / NumOuts, DL, StackPtr.getValueType()));
19465 DAG.getMachineFunction(), SPFI, I * 16 / NumOuts);
19466 SDValue Load = DAG.getExtLoad(
19467 N->getOpcode() == ARMISD::MVESEXT ? ISD::SEXTLOAD : ISD::ZEXTLOAD, DL,
19468 VT, Chain, Ptr, MPI, LoadVT, Align(4));
19469 Loads.push_back(Load);
19470 }
19471
19472 return DAG.getMergeValues(Loads, DL);
19473}
19474
19476 DAGCombinerInfo &DCI) const {
19477 switch (N->getOpcode()) {
19478 default: break;
19479 case ISD::SELECT_CC:
19480 case ISD::SELECT: return PerformSELECTCombine(N, DCI, Subtarget);
19481 case ISD::VSELECT: return PerformVSELECTCombine(N, DCI, Subtarget);
19482 case ISD::SETCC: return PerformVSetCCToVCTPCombine(N, DCI, Subtarget);
19483 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget);
19484 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget);
19485 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
19486 case ISD::SUB: return PerformSUBCombine(N, DCI, Subtarget);
19487 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
19488 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
19489 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
19490 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
19491 case ISD::BRCOND:
19492 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget);
19493 case ARMISD::ADDC:
19494 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget);
19495 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget);
19496 case ARMISD::BFI: return PerformBFICombine(N, DCI.DAG);
19497 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
19498 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
19499 case ARMISD::VMOVhr: return PerformVMOVhrCombine(N, DCI);
19500 case ARMISD::VMOVrh: return PerformVMOVrhCombine(N, DCI.DAG);
19501 case ARMISD::VMOVrs:
19502 return PerformVMOVrsCombine(N, DCI.DAG);
19503 case ISD::STORE: return PerformSTORECombine(N, DCI, Subtarget);
19504 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
19507 return PerformExtractEltCombine(N, DCI, Subtarget);
19511 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI, Subtarget);
19512 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI.DAG, Subtarget);
19513 case ISD::FP_TO_SINT:
19514 case ISD::FP_TO_UINT:
19515 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
19516 case ISD::FADD:
19517 return PerformFADDCombine(N, DCI.DAG, Subtarget);
19518 case ISD::FMUL:
19519 return PerformVMulVCTPCombine(N, DCI.DAG, Subtarget);
19521 return PerformIntrinsicCombine(N, DCI);
19522 case ISD::SHL:
19523 case ISD::SRA:
19524 case ISD::SRL:
19525 return PerformShiftCombine(N, DCI, Subtarget);
19526 case ISD::SIGN_EXTEND:
19527 case ISD::ZERO_EXTEND:
19528 case ISD::ANY_EXTEND:
19529 return PerformExtendCombine(N, DCI.DAG, Subtarget);
19530 case ISD::FP_EXTEND:
19531 return PerformFPExtendCombine(N, DCI.DAG, Subtarget);
19532 case ISD::SMIN:
19533 case ISD::UMIN:
19534 case ISD::SMAX:
19535 case ISD::UMAX:
19536 return PerformMinMaxCombine(N, DCI.DAG, Subtarget);
19537 case ARMISD::CMOV:
19538 return PerformCMOVCombine(N, DCI.DAG);
19539 case ARMISD::BRCOND:
19540 return PerformBRCONDCombine(N, DCI.DAG);
19541 case ARMISD::CMPZ:
19542 return PerformCMPZCombine(N, DCI.DAG);
19543 case ARMISD::CSINC:
19544 case ARMISD::CSINV:
19545 case ARMISD::CSNEG:
19546 return PerformCSETCombine(N, DCI.DAG);
19547 case ISD::LOAD:
19548 return PerformLOADCombine(N, DCI, Subtarget);
19550 return PerformVECTOR_DEINTERLEAVECombine(N, DCI, Subtarget);
19551 case ARMISD::VLD1DUP:
19552 case ARMISD::VLD2DUP:
19553 case ARMISD::VLD3DUP:
19554 case ARMISD::VLD4DUP:
19555 return PerformVLDCombine(N, DCI);
19557 return PerformARMBUILD_VECTORCombine(N, DCI);
19558 case ISD::BITCAST:
19559 return PerformBITCASTCombine(N, DCI, Subtarget);
19560 case ARMISD::PREDICATE_CAST:
19561 return PerformPREDICATE_CASTCombine(N, DCI);
19562 case ARMISD::VECTOR_REG_CAST:
19563 return PerformVECTOR_REG_CASTCombine(N, DCI.DAG, Subtarget);
19564 case ARMISD::MVETRUNC:
19565 return PerformMVETruncCombine(N, DCI);
19566 case ARMISD::MVESEXT:
19567 case ARMISD::MVEZEXT:
19568 return PerformMVEExtCombine(N, DCI);
19569 case ARMISD::VCMP:
19570 return PerformVCMPCombine(N, DCI.DAG, Subtarget);
19571 case ISD::VECREDUCE_ADD:
19572 return PerformVECREDUCE_ADDCombine(N, DCI.DAG, Subtarget);
19573 case ARMISD::VADDVs:
19574 case ARMISD::VADDVu:
19575 case ARMISD::VADDLVs:
19576 case ARMISD::VADDLVu:
19577 case ARMISD::VADDLVAs:
19578 case ARMISD::VADDLVAu:
19579 case ARMISD::VMLAVs:
19580 case ARMISD::VMLAVu:
19581 case ARMISD::VMLALVs:
19582 case ARMISD::VMLALVu:
19583 case ARMISD::VMLALVAs:
19584 case ARMISD::VMLALVAu:
19585 return PerformReduceShuffleCombine(N, DCI.DAG);
19586 case ARMISD::VMOVN:
19587 return PerformVMOVNCombine(N, DCI);
19588 case ARMISD::VQMOVNs:
19589 case ARMISD::VQMOVNu:
19590 return PerformVQMOVNCombine(N, DCI);
19591 case ARMISD::VQDMULH:
19592 return PerformVQDMULHCombine(N, DCI);
19593 case ARMISD::ASRL:
19594 case ARMISD::LSRL:
19595 case ARMISD::LSLL:
19596 return PerformLongShiftCombine(N, DCI.DAG);
19597 case ARMISD::SMULWB: {
19598 unsigned BitWidth = N->getValueType(0).getSizeInBits();
19599 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
19600 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
19601 return SDValue();
19602 break;
19603 }
19604 case ARMISD::SMULWT: {
19605 unsigned BitWidth = N->getValueType(0).getSizeInBits();
19606 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
19607 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
19608 return SDValue();
19609 break;
19610 }
19611 case ARMISD::SMLALBB:
19612 case ARMISD::QADD16b:
19613 case ARMISD::QSUB16b:
19614 case ARMISD::UQADD16b:
19615 case ARMISD::UQSUB16b: {
19616 unsigned BitWidth = N->getValueType(0).getSizeInBits();
19617 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
19618 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
19619 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
19620 return SDValue();
19621 break;
19622 }
19623 case ARMISD::SMLALBT: {
19624 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
19625 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
19626 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
19627 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
19628 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
19629 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
19630 return SDValue();
19631 break;
19632 }
19633 case ARMISD::SMLALTB: {
19634 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
19635 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
19636 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
19637 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
19638 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
19639 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
19640 return SDValue();
19641 break;
19642 }
19643 case ARMISD::SMLALTT: {
19644 unsigned BitWidth = N->getValueType(0).getSizeInBits();
19645 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
19646 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
19647 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
19648 return SDValue();
19649 break;
19650 }
19651 case ARMISD::QADD8b:
19652 case ARMISD::QSUB8b:
19653 case ARMISD::UQADD8b:
19654 case ARMISD::UQSUB8b: {
19655 unsigned BitWidth = N->getValueType(0).getSizeInBits();
19656 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
19657 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
19658 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
19659 return SDValue();
19660 break;
19661 }
19662 case ARMISD::VBSP:
19663 if (N->getOperand(1) == N->getOperand(2))
19664 return N->getOperand(1);
19665 return SDValue();
19668 switch (N->getConstantOperandVal(1)) {
19669 case Intrinsic::arm_neon_vld1:
19670 case Intrinsic::arm_neon_vld1x2:
19671 case Intrinsic::arm_neon_vld1x3:
19672 case Intrinsic::arm_neon_vld1x4:
19673 case Intrinsic::arm_neon_vld2:
19674 case Intrinsic::arm_neon_vld3:
19675 case Intrinsic::arm_neon_vld4:
19676 case Intrinsic::arm_neon_vld2lane:
19677 case Intrinsic::arm_neon_vld3lane:
19678 case Intrinsic::arm_neon_vld4lane:
19679 case Intrinsic::arm_neon_vld2dup:
19680 case Intrinsic::arm_neon_vld3dup:
19681 case Intrinsic::arm_neon_vld4dup:
19682 case Intrinsic::arm_neon_vst1:
19683 case Intrinsic::arm_neon_vst1x2:
19684 case Intrinsic::arm_neon_vst1x3:
19685 case Intrinsic::arm_neon_vst1x4:
19686 case Intrinsic::arm_neon_vst2:
19687 case Intrinsic::arm_neon_vst3:
19688 case Intrinsic::arm_neon_vst4:
19689 case Intrinsic::arm_neon_vst2lane:
19690 case Intrinsic::arm_neon_vst3lane:
19691 case Intrinsic::arm_neon_vst4lane:
19692 return PerformVLDCombine(N, DCI);
19693 case Intrinsic::arm_mve_vld2q:
19694 case Intrinsic::arm_mve_vld4q:
19695 case Intrinsic::arm_mve_vst2q:
19696 case Intrinsic::arm_mve_vst4q:
19697 return PerformMVEVLDCombine(N, DCI);
19698 default: break;
19699 }
19700 break;
19701 }
19702 return SDValue();
19703}
19704
19706 EVT VT) const {
19707 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
19708}
19709
19711 Align Alignment,
19713 unsigned *Fast) const {
19714 // Depends what it gets converted into if the type is weird.
19715 if (!VT.isSimple())
19716 return false;
19717
19718 // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus
19719 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
19720 auto Ty = VT.getSimpleVT().SimpleTy;
19721
19722 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
19723 // Unaligned access can use (for example) LRDB, LRDH, LDR
19724 if (AllowsUnaligned) {
19725 if (Fast)
19726 *Fast = Subtarget->hasV7Ops();
19727 return true;
19728 }
19729 }
19730
19731 if (Ty == MVT::f64 || Ty == MVT::v2f64) {
19732 // For any little-endian targets with neon, we can support unaligned ld/st
19733 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
19734 // A big-endian target may also explicitly support unaligned accesses
19735 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
19736 if (Fast)
19737 *Fast = 1;
19738 return true;
19739 }
19740 }
19741
19742 if (!Subtarget->hasMVEIntegerOps())
19743 return false;
19744
19745 // These are for predicates
19746 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1 ||
19747 Ty == MVT::v2i1)) {
19748 if (Fast)
19749 *Fast = 1;
19750 return true;
19751 }
19752
19753 // These are for truncated stores/narrowing loads. They are fine so long as
19754 // the alignment is at least the size of the item being loaded
19755 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
19756 Alignment >= VT.getScalarSizeInBits() / 8) {
19757 if (Fast)
19758 *Fast = true;
19759 return true;
19760 }
19761
19762 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
19763 // VSTRW.U32 all store the vector register in exactly the same format, and
19764 // differ only in the range of their immediate offset field and the required
19765 // alignment. So there is always a store that can be used, regardless of
19766 // actual type.
19767 //
19768 // For big endian, that is not the case. But can still emit a (VSTRB.U8;
19769 // VREV64.8) pair and get the same effect. This will likely be better than
19770 // aligning the vector through the stack.
19771 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
19772 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
19773 Ty == MVT::v2f64) {
19774 if (Fast)
19775 *Fast = 1;
19776 return true;
19777 }
19778
19779 return false;
19780}
19781
19783 LLVMContext &Context, const MemOp &Op,
19784 const AttributeList &FuncAttributes) const {
19785 // See if we can use NEON instructions for this...
19786 if ((Op.isMemcpyOrMemmove() || Op.isZeroMemset()) && Subtarget->hasNEON() &&
19787 !FuncAttributes.hasFnAttr(Attribute::NoImplicitFloat)) {
19788 unsigned Fast;
19789 if (Op.size() >= 16 &&
19790 (Op.isAligned(Align(16)) ||
19791 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, Align(1),
19793 Fast))) {
19794 return MVT::v2f64;
19795 } else if (Op.size() >= 8 &&
19796 (Op.isAligned(Align(8)) ||
19798 MVT::f64, 0, Align(1), MachineMemOperand::MONone, &Fast) &&
19799 Fast))) {
19800 return MVT::f64;
19801 }
19802 }
19803
19804 // Let the target-independent logic figure it out.
19805 return MVT::Other;
19806}
19807
19808// 64-bit integers are split into their high and low parts and held in two
19809// different registers, so the trunc is free since the low register can just
19810// be used.
19811bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
19812 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
19813 return false;
19814 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
19815 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
19816 return (SrcBits == 64 && DestBits == 32);
19817}
19818
19820 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
19821 !DstVT.isInteger())
19822 return false;
19823 unsigned SrcBits = SrcVT.getSizeInBits();
19824 unsigned DestBits = DstVT.getSizeInBits();
19825 return (SrcBits == 64 && DestBits == 32);
19826}
19827
19829 if (Val.getOpcode() != ISD::LOAD)
19830 return false;
19831
19832 EVT VT1 = Val.getValueType();
19833 if (!VT1.isSimple() || !VT1.isInteger() ||
19834 !VT2.isSimple() || !VT2.isInteger())
19835 return false;
19836
19837 switch (VT1.getSimpleVT().SimpleTy) {
19838 default: break;
19839 case MVT::i1:
19840 case MVT::i8:
19841 case MVT::i16:
19842 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
19843 return true;
19844 }
19845
19846 return false;
19847}
19848
19850 if (!VT.isSimple())
19851 return false;
19852
19853 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
19854 // negate values directly (fneg is free). So, we don't want to let the DAG
19855 // combiner rewrite fneg into xors and some other instructions. For f16 and
19856 // FullFP16 argument passing, some bitcast nodes may be introduced,
19857 // triggering this DAG combine rewrite, so we are avoiding that with this.
19858 switch (VT.getSimpleVT().SimpleTy) {
19859 default: break;
19860 case MVT::f16:
19861 return Subtarget->hasFullFP16();
19862 }
19863
19864 return false;
19865}
19866
19868 if (!Subtarget->hasMVEIntegerOps())
19869 return nullptr;
19870 Type *SVIType = SVI->getType();
19871 Type *ScalarType = SVIType->getScalarType();
19872
19873 if (ScalarType->isFloatTy())
19874 return Type::getInt32Ty(SVIType->getContext());
19875 if (ScalarType->isHalfTy())
19876 return Type::getInt16Ty(SVIType->getContext());
19877 return nullptr;
19878}
19879
19881 EVT VT = ExtVal.getValueType();
19882
19883 if (!isTypeLegal(VT))
19884 return false;
19885
19886 if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) {
19887 if (Ld->isExpandingLoad())
19888 return false;
19889 }
19890
19891 if (Subtarget->hasMVEIntegerOps())
19892 return true;
19893
19894 // Don't create a loadext if we can fold the extension into a wide/long
19895 // instruction.
19896 // If there's more than one user instruction, the loadext is desirable no
19897 // matter what. There can be two uses by the same instruction.
19898 if (ExtVal->use_empty() ||
19899 !ExtVal->user_begin()->isOnlyUserOf(ExtVal.getNode()))
19900 return true;
19901
19902 SDNode *U = *ExtVal->user_begin();
19903 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
19904 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
19905 return false;
19906
19907 return true;
19908}
19909
19911 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19912 return false;
19913
19914 if (!isTypeLegal(EVT::getEVT(Ty1)))
19915 return false;
19916
19917 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19918
19919 // Assuming the caller doesn't have a zeroext or signext return parameter,
19920 // truncation all the way down to i1 is valid.
19921 return true;
19922}
19923
19924/// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster
19925/// than a pair of fmul and fadd instructions. fmuladd intrinsics will be
19926/// expanded to FMAs when this method returns true, otherwise fmuladd is
19927/// expanded to fmul + fadd.
19928///
19929/// ARM supports both fused and unfused multiply-add operations; we already
19930/// lower a pair of fmul and fadd to the latter so it's not clear that there
19931/// would be a gain or that the gain would be worthwhile enough to risk
19932/// correctness bugs.
19933///
19934/// For MVE, we set this to true as it helps simplify the need for some
19935/// patterns (and we don't have the non-fused floating point instruction).
19936bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
19937 EVT VT) const {
19938 if (Subtarget->useSoftFloat())
19939 return false;
19940
19941 if (!VT.isSimple())
19942 return false;
19943
19944 switch (VT.getSimpleVT().SimpleTy) {
19945 case MVT::v4f32:
19946 case MVT::v8f16:
19947 return Subtarget->hasMVEFloatOps();
19948 case MVT::f16:
19949 return Subtarget->useFPVFMx16();
19950 case MVT::f32:
19951 return Subtarget->useFPVFMx();
19952 case MVT::f64:
19953 return Subtarget->useFPVFMx64();
19954 default:
19955 break;
19956 }
19957
19958 return false;
19959}
19960
19961static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
19962 if (V < 0)
19963 return false;
19964
19965 unsigned Scale = 1;
19966 switch (VT.getSimpleVT().SimpleTy) {
19967 case MVT::i1:
19968 case MVT::i8:
19969 // Scale == 1;
19970 break;
19971 case MVT::i16:
19972 // Scale == 2;
19973 Scale = 2;
19974 break;
19975 default:
19976 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
19977 // Scale == 4;
19978 Scale = 4;
19979 break;
19980 }
19981
19982 if ((V & (Scale - 1)) != 0)
19983 return false;
19984 return isUInt<5>(V / Scale);
19985}
19986
19987static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
19988 const ARMSubtarget *Subtarget) {
19989 if (!VT.isInteger() && !VT.isFloatingPoint())
19990 return false;
19991 if (VT.isVector() && Subtarget->hasNEON())
19992 return false;
19993 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
19994 !Subtarget->hasMVEFloatOps())
19995 return false;
19996
19997 bool IsNeg = false;
19998 if (V < 0) {
19999 IsNeg = true;
20000 V = -V;
20001 }
20002
20003 unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U);
20004
20005 // MVE: size * imm7
20006 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
20007 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
20008 case MVT::i32:
20009 case MVT::f32:
20010 return isShiftedUInt<7,2>(V);
20011 case MVT::i16:
20012 case MVT::f16:
20013 return isShiftedUInt<7,1>(V);
20014 case MVT::i8:
20015 return isUInt<7>(V);
20016 default:
20017 return false;
20018 }
20019 }
20020
20021 // half VLDR: 2 * imm8
20022 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
20023 return isShiftedUInt<8, 1>(V);
20024 // VLDR and LDRD: 4 * imm8
20025 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
20026 return isShiftedUInt<8, 2>(V);
20027
20028 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
20029 // + imm12 or - imm8
20030 if (IsNeg)
20031 return isUInt<8>(V);
20032 return isUInt<12>(V);
20033 }
20034
20035 return false;
20036}
20037
20038/// isLegalAddressImmediate - Return true if the integer value can be used
20039/// as the offset of the target addressing mode for load / store of the
20040/// given type.
20041static bool isLegalAddressImmediate(int64_t V, EVT VT,
20042 const ARMSubtarget *Subtarget) {
20043 if (V == 0)
20044 return true;
20045
20046 if (!VT.isSimple())
20047 return false;
20048
20049 if (Subtarget->isThumb1Only())
20050 return isLegalT1AddressImmediate(V, VT);
20051 else if (Subtarget->isThumb2())
20053
20054 // ARM mode.
20055 if (V < 0)
20056 V = - V;
20057 switch (VT.getSimpleVT().SimpleTy) {
20058 default: return false;
20059 case MVT::i1:
20060 case MVT::i8:
20061 case MVT::i32:
20062 // +- imm12
20063 return isUInt<12>(V);
20064 case MVT::i16:
20065 // +- imm8
20066 return isUInt<8>(V);
20067 case MVT::f32:
20068 case MVT::f64:
20069 if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
20070 return false;
20071 return isShiftedUInt<8, 2>(V);
20072 }
20073}
20074
20076 EVT VT) const {
20077 int Scale = AM.Scale;
20078 if (Scale < 0)
20079 return false;
20080
20081 switch (VT.getSimpleVT().SimpleTy) {
20082 default: return false;
20083 case MVT::i1:
20084 case MVT::i8:
20085 case MVT::i16:
20086 case MVT::i32:
20087 if (Scale == 1)
20088 return true;
20089 // r + r << imm
20090 Scale = Scale & ~1;
20091 return Scale == 2 || Scale == 4 || Scale == 8;
20092 case MVT::i64:
20093 // FIXME: What are we trying to model here? ldrd doesn't have an r + r
20094 // version in Thumb mode.
20095 // r + r
20096 if (Scale == 1)
20097 return true;
20098 // r * 2 (this can be lowered to r + r).
20099 if (!AM.HasBaseReg && Scale == 2)
20100 return true;
20101 return false;
20102 case MVT::isVoid:
20103 // Note, we allow "void" uses (basically, uses that aren't loads or
20104 // stores), because arm allows folding a scale into many arithmetic
20105 // operations. This should be made more precise and revisited later.
20106
20107 // Allow r << imm, but the imm has to be a multiple of two.
20108 if (Scale & 1) return false;
20109 return isPowerOf2_32(Scale);
20110 }
20111}
20112
20114 EVT VT) const {
20115 const int Scale = AM.Scale;
20116
20117 // Negative scales are not supported in Thumb1.
20118 if (Scale < 0)
20119 return false;
20120
20121 // Thumb1 addressing modes do not support register scaling excepting the
20122 // following cases:
20123 // 1. Scale == 1 means no scaling.
20124 // 2. Scale == 2 this can be lowered to r + r if there is no base register.
20125 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
20126}
20127
20128/// isLegalAddressingMode - Return true if the addressing mode represented
20129/// by AM is legal for this target, for a load/store of the specified type.
20131 const AddrMode &AM, Type *Ty,
20132 unsigned AS, Instruction *I) const {
20133 EVT VT = getValueType(DL, Ty, true);
20134 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
20135 return false;
20136
20137 // Can never fold addr of global into load/store.
20138 if (AM.BaseGV)
20139 return false;
20140
20141 switch (AM.Scale) {
20142 case 0: // no scale reg, must be "r+i" or "r", or "i".
20143 break;
20144 default:
20145 // ARM doesn't support any R+R*scale+imm addr modes.
20146 if (AM.BaseOffs)
20147 return false;
20148
20149 if (!VT.isSimple())
20150 return false;
20151
20152 if (Subtarget->isThumb1Only())
20153 return isLegalT1ScaledAddressingMode(AM, VT);
20154
20155 if (Subtarget->isThumb2())
20156 return isLegalT2ScaledAddressingMode(AM, VT);
20157
20158 int Scale = AM.Scale;
20159 switch (VT.getSimpleVT().SimpleTy) {
20160 default: return false;
20161 case MVT::i1:
20162 case MVT::i8:
20163 case MVT::i32:
20164 if (Scale < 0) Scale = -Scale;
20165 if (Scale == 1)
20166 return true;
20167 // r + r << imm
20168 return isPowerOf2_32(Scale & ~1);
20169 case MVT::i16:
20170 case MVT::i64:
20171 // r +/- r
20172 if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
20173 return true;
20174 // r * 2 (this can be lowered to r + r).
20175 if (!AM.HasBaseReg && Scale == 2)
20176 return true;
20177 return false;
20178
20179 case MVT::isVoid:
20180 // Note, we allow "void" uses (basically, uses that aren't loads or
20181 // stores), because arm allows folding a scale into many arithmetic
20182 // operations. This should be made more precise and revisited later.
20183
20184 // Allow r << imm, but the imm has to be a multiple of two.
20185 if (Scale & 1) return false;
20186 return isPowerOf2_32(Scale);
20187 }
20188 }
20189 return true;
20190}
20191
20192/// isLegalICmpImmediate - Return true if the specified immediate is legal
20193/// icmp immediate, that is the target has icmp instructions which can compare
20194/// a register against the immediate without having to materialize the
20195/// immediate into a register.
20197 // Thumb2 and ARM modes can use cmn for negative immediates.
20198 if (!Subtarget->isThumb())
20199 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
20201 if (Subtarget->isThumb2())
20202 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
20204 // Thumb1 doesn't have cmn, and only 8-bit immediates.
20205 return Imm >= 0 && Imm <= 255;
20206}
20207
20208/// isLegalAddImmediate - Return true if the specified immediate is a legal add
20209/// *or sub* immediate, that is the target has add or sub instructions which can
20210/// add a register with the immediate without having to materialize the
20211/// immediate into a register.
20213 // Same encoding for add/sub, just flip the sign.
20214 uint64_t AbsImm = AbsoluteValue(Imm);
20215 if (!Subtarget->isThumb())
20216 return ARM_AM::getSOImmVal(AbsImm) != -1;
20217 if (Subtarget->isThumb2())
20218 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
20219 // Thumb1 only has 8-bit unsigned immediate.
20220 return AbsImm <= 255;
20221}
20222
20223// Return false to prevent folding
20224// (mul (add r, c0), c1) -> (add (mul r, c1), c0*c1) in DAGCombine,
20225// if the folding leads to worse code.
20227 SDValue ConstNode) const {
20228 // Let the DAGCombiner decide for vector types and large types.
20229 const EVT VT = AddNode.getValueType();
20230 if (VT.isVector() || VT.getScalarSizeInBits() > 32)
20231 return true;
20232
20233 // It is worse if c0 is legal add immediate, while c1*c0 is not
20234 // and has to be composed by at least two instructions.
20235 const ConstantSDNode *C0Node = cast<ConstantSDNode>(AddNode.getOperand(1));
20236 const ConstantSDNode *C1Node = cast<ConstantSDNode>(ConstNode);
20237 const int64_t C0 = C0Node->getSExtValue();
20238 APInt CA = C0Node->getAPIntValue() * C1Node->getAPIntValue();
20240 return true;
20241 if (ConstantMaterializationCost((unsigned)CA.getZExtValue(), Subtarget) > 1)
20242 return false;
20243
20244 // Default to true and let the DAGCombiner decide.
20245 return true;
20246}
20247
20249 bool isSEXTLoad, SDValue &Base,
20250 SDValue &Offset, bool &isInc,
20251 SelectionDAG &DAG) {
20252 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
20253 return false;
20254
20255 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
20256 // AddressingMode 3
20257 Base = Ptr->getOperand(0);
20259 int RHSC = (int)RHS->getZExtValue();
20260 if (RHSC < 0 && RHSC > -256) {
20261 assert(Ptr->getOpcode() == ISD::ADD);
20262 isInc = false;
20263 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
20264 return true;
20265 }
20266 }
20267 isInc = (Ptr->getOpcode() == ISD::ADD);
20268 Offset = Ptr->getOperand(1);
20269 return true;
20270 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
20271 // AddressingMode 2
20273 int RHSC = (int)RHS->getZExtValue();
20274 if (RHSC < 0 && RHSC > -0x1000) {
20275 assert(Ptr->getOpcode() == ISD::ADD);
20276 isInc = false;
20277 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
20278 Base = Ptr->getOperand(0);
20279 return true;
20280 }
20281 }
20282
20283 if (Ptr->getOpcode() == ISD::ADD) {
20284 isInc = true;
20285 ARM_AM::ShiftOpc ShOpcVal=
20287 if (ShOpcVal != ARM_AM::no_shift) {
20288 Base = Ptr->getOperand(1);
20289 Offset = Ptr->getOperand(0);
20290 } else {
20291 Base = Ptr->getOperand(0);
20292 Offset = Ptr->getOperand(1);
20293 }
20294 return true;
20295 }
20296
20297 isInc = (Ptr->getOpcode() == ISD::ADD);
20298 Base = Ptr->getOperand(0);
20299 Offset = Ptr->getOperand(1);
20300 return true;
20301 }
20302
20303 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
20304 return false;
20305}
20306
20308 bool isSEXTLoad, SDValue &Base,
20309 SDValue &Offset, bool &isInc,
20310 SelectionDAG &DAG) {
20311 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
20312 return false;
20313
20314 Base = Ptr->getOperand(0);
20316 int RHSC = (int)RHS->getZExtValue();
20317 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
20318 assert(Ptr->getOpcode() == ISD::ADD);
20319 isInc = false;
20320 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
20321 return true;
20322 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
20323 isInc = Ptr->getOpcode() == ISD::ADD;
20324 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
20325 return true;
20326 }
20327 }
20328
20329 return false;
20330}
20331
20332static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, Align Alignment,
20333 bool isSEXTLoad, bool IsMasked, bool isLE,
20335 bool &isInc, SelectionDAG &DAG) {
20336 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
20337 return false;
20338 if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
20339 return false;
20340
20341 // We allow LE non-masked loads to change the type (for example use a vldrb.8
20342 // as opposed to a vldrw.32). This can allow extra addressing modes or
20343 // alignments for what is otherwise an equivalent instruction.
20344 bool CanChangeType = isLE && !IsMasked;
20345
20347 int RHSC = (int)RHS->getZExtValue();
20348
20349 auto IsInRange = [&](int RHSC, int Limit, int Scale) {
20350 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
20351 assert(Ptr->getOpcode() == ISD::ADD);
20352 isInc = false;
20353 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
20354 return true;
20355 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
20356 isInc = Ptr->getOpcode() == ISD::ADD;
20357 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
20358 return true;
20359 }
20360 return false;
20361 };
20362
20363 // Try to find a matching instruction based on s/zext, Alignment, Offset and
20364 // (in BE/masked) type.
20365 Base = Ptr->getOperand(0);
20366 if (VT == MVT::v4i16) {
20367 if (Alignment >= 2 && IsInRange(RHSC, 0x80, 2))
20368 return true;
20369 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
20370 if (IsInRange(RHSC, 0x80, 1))
20371 return true;
20372 } else if (Alignment >= 4 &&
20373 (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) &&
20374 IsInRange(RHSC, 0x80, 4))
20375 return true;
20376 else if (Alignment >= 2 &&
20377 (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) &&
20378 IsInRange(RHSC, 0x80, 2))
20379 return true;
20380 else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
20381 return true;
20382 return false;
20383}
20384
20385/// getPreIndexedAddressParts - returns true by value, base pointer and
20386/// offset pointer and addressing mode by reference if the node's address
20387/// can be legally represented as pre-indexed load / store address.
20388bool
20390 SDValue &Offset,
20392 SelectionDAG &DAG) const {
20393 if (Subtarget->isThumb1Only())
20394 return false;
20395
20396 EVT VT;
20397 SDValue Ptr;
20398 Align Alignment;
20399 unsigned AS = 0;
20400 bool isSEXTLoad = false;
20401 bool IsMasked = false;
20402 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
20403 Ptr = LD->getBasePtr();
20404 VT = LD->getMemoryVT();
20405 Alignment = LD->getAlign();
20406 AS = LD->getAddressSpace();
20407 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
20408 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
20409 Ptr = ST->getBasePtr();
20410 VT = ST->getMemoryVT();
20411 Alignment = ST->getAlign();
20412 AS = ST->getAddressSpace();
20413 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
20414 Ptr = LD->getBasePtr();
20415 VT = LD->getMemoryVT();
20416 Alignment = LD->getAlign();
20417 AS = LD->getAddressSpace();
20418 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
20419 IsMasked = true;
20421 Ptr = ST->getBasePtr();
20422 VT = ST->getMemoryVT();
20423 Alignment = ST->getAlign();
20424 AS = ST->getAddressSpace();
20425 IsMasked = true;
20426 } else
20427 return false;
20428
20429 unsigned Fast = 0;
20430 if (!allowsMisalignedMemoryAccesses(VT, AS, Alignment,
20432 // Only generate post-increment or pre-increment forms when a real
20433 // hardware instruction exists for them. Do not emit postinc/preinc
20434 // if the operation will end up as a libcall.
20435 return false;
20436 }
20437
20438 bool isInc;
20439 bool isLegal = false;
20440 if (VT.isVector())
20441 isLegal = Subtarget->hasMVEIntegerOps() &&
20443 Ptr.getNode(), VT, Alignment, isSEXTLoad, IsMasked,
20444 Subtarget->isLittle(), Base, Offset, isInc, DAG);
20445 else {
20446 if (Subtarget->isThumb2())
20447 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
20448 Offset, isInc, DAG);
20449 else
20450 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
20451 Offset, isInc, DAG);
20452 }
20453 if (!isLegal)
20454 return false;
20455
20456 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
20457 return true;
20458}
20459
20460/// getPostIndexedAddressParts - returns true by value, base pointer and
20461/// offset pointer and addressing mode by reference if this node can be
20462/// combined with a load / store to form a post-indexed load / store.
20464 SDValue &Base,
20465 SDValue &Offset,
20467 SelectionDAG &DAG) const {
20468 EVT VT;
20469 SDValue Ptr;
20470 Align Alignment;
20471 bool isSEXTLoad = false, isNonExt;
20472 bool IsMasked = false;
20473 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
20474 VT = LD->getMemoryVT();
20475 Ptr = LD->getBasePtr();
20476 Alignment = LD->getAlign();
20477 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
20478 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
20479 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
20480 VT = ST->getMemoryVT();
20481 Ptr = ST->getBasePtr();
20482 Alignment = ST->getAlign();
20483 isNonExt = !ST->isTruncatingStore();
20484 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
20485 VT = LD->getMemoryVT();
20486 Ptr = LD->getBasePtr();
20487 Alignment = LD->getAlign();
20488 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
20489 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
20490 IsMasked = true;
20492 VT = ST->getMemoryVT();
20493 Ptr = ST->getBasePtr();
20494 Alignment = ST->getAlign();
20495 isNonExt = !ST->isTruncatingStore();
20496 IsMasked = true;
20497 } else
20498 return false;
20499
20500 if (Subtarget->isThumb1Only()) {
20501 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
20502 // must be non-extending/truncating, i32, with an offset of 4.
20503 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
20504 if (Op->getOpcode() != ISD::ADD || !isNonExt)
20505 return false;
20506 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
20507 if (!RHS || RHS->getZExtValue() != 4)
20508 return false;
20509 if (Alignment < Align(4))
20510 return false;
20511
20512 Offset = Op->getOperand(1);
20513 Base = Op->getOperand(0);
20514 AM = ISD::POST_INC;
20515 return true;
20516 }
20517
20518 bool isInc;
20519 bool isLegal = false;
20520 if (VT.isVector())
20521 isLegal = Subtarget->hasMVEIntegerOps() &&
20522 getMVEIndexedAddressParts(Op, VT, Alignment, isSEXTLoad, IsMasked,
20523 Subtarget->isLittle(), Base, Offset,
20524 isInc, DAG);
20525 else {
20526 if (Subtarget->isThumb2())
20527 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
20528 isInc, DAG);
20529 else
20530 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
20531 isInc, DAG);
20532 }
20533 if (!isLegal)
20534 return false;
20535
20536 if (Ptr != Base) {
20537 // Swap base ptr and offset to catch more post-index load / store when
20538 // it's legal. In Thumb2 mode, offset must be an immediate.
20539 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
20540 !Subtarget->isThumb2())
20542
20543 // Post-indexed load / store update the base pointer.
20544 if (Ptr != Base)
20545 return false;
20546 }
20547
20548 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
20549 return true;
20550}
20551
20554 const APInt &DemandedElts,
20555 const SelectionDAG &DAG,
20556 unsigned Depth) const {
20557 unsigned BitWidth = Known.getBitWidth();
20558 Known.resetAll();
20559 switch (Op.getOpcode()) {
20560 default: break;
20561 case ARMISD::ADDC:
20562 case ARMISD::ADDE:
20563 case ARMISD::SUBC:
20564 case ARMISD::SUBE:
20565 // Special cases when we convert a carry to a boolean.
20566 if (Op.getResNo() == 0) {
20567 SDValue LHS = Op.getOperand(0);
20568 SDValue RHS = Op.getOperand(1);
20569 // (ADDE 0, 0, C) will give us a single bit.
20570 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
20571 isNullConstant(RHS)) {
20573 return;
20574 }
20575 }
20576 break;
20577 case ARMISD::CMOV: {
20578 // Bits are known zero/one if known on the LHS and RHS.
20579 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
20580 if (Known.isUnknown())
20581 return;
20582
20583 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
20584 Known = Known.intersectWith(KnownRHS);
20585 return;
20586 }
20588 Intrinsic::ID IntID =
20589 static_cast<Intrinsic::ID>(Op->getConstantOperandVal(1));
20590 switch (IntID) {
20591 default: return;
20592 case Intrinsic::arm_ldaex:
20593 case Intrinsic::arm_ldrex: {
20594 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
20595 unsigned MemBits = VT.getScalarSizeInBits();
20596 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
20597 return;
20598 }
20599 }
20600 }
20601 case ARMISD::BFI: {
20602 // Conservatively, we can recurse down the first operand
20603 // and just mask out all affected bits.
20604 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
20605
20606 // The operand to BFI is already a mask suitable for removing the bits it
20607 // sets.
20608 const APInt &Mask = Op.getConstantOperandAPInt(2);
20609 Known.Zero &= Mask;
20610 Known.One &= Mask;
20611 return;
20612 }
20613 case ARMISD::VGETLANEs:
20614 case ARMISD::VGETLANEu: {
20615 const SDValue &SrcSV = Op.getOperand(0);
20616 EVT VecVT = SrcSV.getValueType();
20617 assert(VecVT.isVector() && "VGETLANE expected a vector type");
20618 const unsigned NumSrcElts = VecVT.getVectorNumElements();
20619 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
20620 assert(Pos->getAPIntValue().ult(NumSrcElts) &&
20621 "VGETLANE index out of bounds");
20622 unsigned Idx = Pos->getZExtValue();
20623 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
20624 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
20625
20626 EVT VT = Op.getValueType();
20627 const unsigned DstSz = VT.getScalarSizeInBits();
20628 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
20629 (void)SrcSz;
20630 assert(SrcSz == Known.getBitWidth());
20631 assert(DstSz > SrcSz);
20632 if (Op.getOpcode() == ARMISD::VGETLANEs)
20633 Known = Known.sext(DstSz);
20634 else {
20635 Known = Known.zext(DstSz);
20636 }
20637 assert(DstSz == Known.getBitWidth());
20638 break;
20639 }
20640 case ARMISD::VMOVrh: {
20641 KnownBits KnownOp = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
20642 assert(KnownOp.getBitWidth() == 16);
20643 Known = KnownOp.zext(32);
20644 break;
20645 }
20646 case ARMISD::CSINC:
20647 case ARMISD::CSINV:
20648 case ARMISD::CSNEG: {
20649 KnownBits KnownOp0 = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
20650 KnownBits KnownOp1 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
20651
20652 // The result is either:
20653 // CSINC: KnownOp0 or KnownOp1 + 1
20654 // CSINV: KnownOp0 or ~KnownOp1
20655 // CSNEG: KnownOp0 or KnownOp1 * -1
20656 if (Op.getOpcode() == ARMISD::CSINC)
20657 KnownOp1 =
20658 KnownBits::add(KnownOp1, KnownBits::makeConstant(APInt(32, 1)));
20659 else if (Op.getOpcode() == ARMISD::CSINV)
20660 std::swap(KnownOp1.Zero, KnownOp1.One);
20661 else if (Op.getOpcode() == ARMISD::CSNEG)
20662 KnownOp1 = KnownBits::mul(KnownOp1,
20664
20665 Known = KnownOp0.intersectWith(KnownOp1);
20666 break;
20667 }
20668 case ARMISD::VORRIMM:
20669 case ARMISD::VBICIMM: {
20670 unsigned Encoded = Op.getConstantOperandVal(1);
20671 unsigned DecEltBits = 0;
20672 uint64_t DecodedVal = ARM_AM::decodeVMOVModImm(Encoded, DecEltBits);
20673
20674 unsigned EltBits = Op.getScalarValueSizeInBits();
20675 if (EltBits != DecEltBits) {
20676 // Be conservative: only update Known when EltBits == DecEltBits.
20677 // This is believed to always be true for VORRIMM/VBICIMM today, but if
20678 // that changes in the future, doing nothing here is safer than risking
20679 // subtle bugs.
20680 break;
20681 }
20682
20683 KnownBits KnownLHS = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
20684 bool IsVORR = Op.getOpcode() == ARMISD::VORRIMM;
20685 APInt Imm(DecEltBits, DecodedVal);
20686
20687 Known.One = IsVORR ? (KnownLHS.One | Imm) : (KnownLHS.One & ~Imm);
20688 Known.Zero = IsVORR ? (KnownLHS.Zero & ~Imm) : (KnownLHS.Zero | Imm);
20689 break;
20690 }
20691 }
20692}
20693
20694static bool isLegalLogicalImmediate(unsigned Imm,
20695 const ARMSubtarget *Subtarget) {
20696 if (!Subtarget->isThumb())
20697 return ARM_AM::getSOImmVal(Imm) != -1;
20698 if (Subtarget->isThumb2())
20699 return ARM_AM::getT2SOImmVal(Imm) != -1;
20700 // Thumb1 only has 8-bit unsigned immediate.
20701 return Imm <= 255;
20702}
20703
20704/// Refine i32 AND/OR/XOR with a constant RHS using demanded bits: replace the
20705/// immediate with an equivalent constant that ARM/Thumb can encode as a
20706/// logical immediate (or that selects better lowering), without changing the
20707/// computed result on those demanded bits.
20708static bool optimizeLogicalImm(SDValue Op, unsigned Imm,
20709 const APInt &DemandedBits,
20710 const ARMSubtarget *Subtarget,
20712
20713 if (Imm == 0 || Imm == ~0U)
20714 return false;
20715
20716 unsigned Opc = Op.getOpcode();
20717 unsigned Demanded = DemandedBits.getZExtValue();
20718 EVT VT = Op.getValueType();
20719
20720 unsigned ShrunkImm = Imm & Demanded;
20721 unsigned ExpandedImm = Imm | ~Demanded;
20722
20723 auto IsLegalImm = [ShrunkImm, ExpandedImm](unsigned CandidateImm) -> bool {
20724 return (ShrunkImm & CandidateImm) == ShrunkImm &&
20725 (~ExpandedImm & CandidateImm) == 0;
20726 };
20727 auto UseImm = [Imm, Opc, Op, VT, &TLO](unsigned NewImm) -> bool {
20728 if (NewImm == Imm)
20729 return true;
20730 SDLoc DL(Op);
20731 SDValue NewC = TLO.DAG.getConstant(NewImm, DL, VT);
20732 SDValue NewOp =
20733 TLO.DAG.getNode(Opc, DL, VT, Op.getOperand(0), NewC, Op->getFlags());
20734 return TLO.CombineTo(Op, NewOp);
20735 };
20736
20737 // Shrunk immediate is 0: AND becomes zero; OR/XOR with 0 leaves the other
20738 // operand (still valid on demanded bits).
20739 if (ShrunkImm == 0) {
20740 ++NumOptimizedImms;
20741 return UseImm(ShrunkImm);
20742 }
20743
20744 // If the immediate is all ones: for AND this removes the operation; for
20745 // OR/XOR it remains a transform valid on demanded bits. (Target-independent
20746 // shrink may not fold this, so keep it to avoid obscure combine loops.)
20747 if (ExpandedImm == ~0U) {
20748 ++NumOptimizedImms;
20749 return UseImm(ExpandedImm);
20750 }
20751
20752 // Thumb1: prefer 0xFF / 0xFFFF when they fit the demanded-bit envelope so
20753 // lowering can match uxtb / uxth (AND immediates only; OR/XOR do not use
20754 // that). Run this before strict ShrunkImm: a tight 8-bit ShrunkImm can be
20755 // legal while 0xFF still matches the envelope and yields better isel (uxtb).
20756 if (Opc == ISD::AND && Subtarget->hasV6Ops()) {
20757 if (IsLegalImm(0xFF)) {
20758 ++NumOptimizedImms;
20759 return UseImm(0xFF);
20760 }
20761
20762 if (IsLegalImm(0xFFFF)) {
20763 ++NumOptimizedImms;
20764 return UseImm(0xFFFF);
20765 }
20766 }
20767
20768 // Don't optimize if it is legal.
20770 return false;
20771
20772 // FIXME: Check for BIC being legal causes infinite loop due to target
20773 // independent DAG combine undoing this.
20774
20775 // Prefer strict shrink when ShrunkImm encodes for this target, before
20776 // complement expansion.
20777 if (isLegalLogicalImmediate(ShrunkImm, Subtarget)) {
20778 ++NumOptimizedImms;
20779 return UseImm(ShrunkImm);
20780 }
20781
20782 // Complement expansion: if all undemanded bits are already one, ExpandedImm
20783 // is Imm with every non-demanded bit set. When (~ExpandedImm) < 256, the
20784 // complement fits in an 8-bit unsigned value, i.e. bits 8–31 of ExpandedImm
20785 // are all ones; only the low byte may differ from ~0. Use that expanded
20786 // constant so isel sees a mask shape that fits logical-immediate patterns.
20787 if ((~ExpandedImm) < 256) {
20788 ++NumOptimizedImms;
20789 return UseImm(ExpandedImm);
20790 }
20791
20792 // FIXME: The check for v6 is because this interferes with some ubfx
20793 // optimizations.
20794 if (Opc == ISD::AND && isLegalLogicalImmediate(~ExpandedImm, Subtarget) &&
20795 !Subtarget->hasV6Ops()) {
20796 ++NumOptimizedImms;
20797 return UseImm(ExpandedImm);
20798 }
20799
20800 // Potential improvements:
20801 //
20802 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
20803 // We could try to prefer Thumb1 immediates which can be lowered to a
20804 // two-instruction sequence.
20805
20806 return false;
20807}
20808
20810 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
20811 TargetLoweringOpt &TLO) const {
20812 // Delay this optimization to as late as possible.
20813 if (!TLO.LegalOps)
20814 return false;
20815
20816 EVT VT = Op.getValueType();
20817
20818 // Ignore vectors.
20819 if (VT.isVector())
20820 return false;
20821
20822 unsigned Size = VT.getSizeInBits();
20823
20824 if (Size != 32)
20825 return false;
20826
20827 // Exit early if we demand all bits.
20828 if (DemandedBits.isAllOnes())
20829 return false;
20830
20831 switch (Op.getOpcode()) {
20832 default:
20833 return false;
20834 case ISD::AND:
20835 case ISD::OR:
20836 case ISD::XOR:
20837 break;
20838 }
20839 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
20840 if (!C)
20841 return false;
20842 unsigned Imm = C->getZExtValue();
20843 return optimizeLogicalImm(Op, Imm, DemandedBits, Subtarget, TLO);
20844}
20845
20847 SDValue Op, const APInt &OriginalDemandedBits,
20848 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
20849 unsigned Depth) const {
20850 unsigned Opc = Op.getOpcode();
20851
20852 switch (Opc) {
20853 case ARMISD::ASRL:
20854 case ARMISD::LSRL: {
20855 // If this is result 0 and the other result is unused, see if the demand
20856 // bits allow us to shrink this long shift into a standard small shift in
20857 // the opposite direction.
20858 if (Op.getResNo() == 0 && !Op->hasAnyUseOfValue(1) &&
20859 isa<ConstantSDNode>(Op->getOperand(2))) {
20860 unsigned ShAmt = Op->getConstantOperandVal(2);
20861 if (ShAmt < 32 && OriginalDemandedBits.isSubsetOf(APInt::getAllOnes(32)
20862 << (32 - ShAmt)))
20863 return TLO.CombineTo(
20864 Op, TLO.DAG.getNode(
20865 ISD::SHL, SDLoc(Op), MVT::i32, Op.getOperand(1),
20866 TLO.DAG.getConstant(32 - ShAmt, SDLoc(Op), MVT::i32)));
20867 }
20868 break;
20869 }
20870 case ARMISD::VBICIMM: {
20871 SDValue Op0 = Op.getOperand(0);
20872 unsigned ModImm = Op.getConstantOperandVal(1);
20873 unsigned EltBits = 0;
20874 uint64_t Mask = ARM_AM::decodeVMOVModImm(ModImm, EltBits);
20875 if ((OriginalDemandedBits & Mask) == 0)
20876 return TLO.CombineTo(Op, Op0);
20877 }
20878 }
20879
20881 Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
20882}
20883
20884//===----------------------------------------------------------------------===//
20885// ARM Inline Assembly Support
20886//===----------------------------------------------------------------------===//
20887
20888const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
20889 // At this point, we have to lower this constraint to something else, so we
20890 // lower it to an "r" or "w". However, by doing this we will force the result
20891 // to be in register, while the X constraint is much more permissive.
20892 //
20893 // Although we are correct (we are free to emit anything, without
20894 // constraints), we might break use cases that would expect us to be more
20895 // efficient and emit something else.
20896 if (!Subtarget->hasVFP2Base())
20897 return "r";
20898 if (ConstraintVT.isFloatingPoint())
20899 return "w";
20900 if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
20901 (ConstraintVT.getSizeInBits() == 64 ||
20902 ConstraintVT.getSizeInBits() == 128))
20903 return "w";
20904
20905 return "r";
20906}
20907
20908/// getConstraintType - Given a constraint letter, return the type of
20909/// constraint it is for this target.
20912 unsigned S = Constraint.size();
20913 if (S == 1) {
20914 switch (Constraint[0]) {
20915 default: break;
20916 case 'l': return C_RegisterClass;
20917 case 'w': return C_RegisterClass;
20918 case 'h': return C_RegisterClass;
20919 case 'x': return C_RegisterClass;
20920 case 't': return C_RegisterClass;
20921 case 'j': return C_Immediate; // Constant for movw.
20922 // An address with a single base register. Due to the way we
20923 // currently handle addresses it is the same as an 'r' memory constraint.
20924 case 'Q': return C_Memory;
20925 }
20926 } else if (S == 2) {
20927 switch (Constraint[0]) {
20928 default: break;
20929 case 'T': return C_RegisterClass;
20930 // All 'U+' constraints are addresses.
20931 case 'U': return C_Memory;
20932 }
20933 }
20934 return TargetLowering::getConstraintType(Constraint);
20935}
20936
20937/// Examine constraint type and operand type and determine a weight value.
20938/// This object must already have been set up with the operand type
20939/// and the current alternative constraint selected.
20942 AsmOperandInfo &info, const char *constraint) const {
20944 Value *CallOperandVal = info.CallOperandVal;
20945 // If we don't have a value, we can't do a match,
20946 // but allow it at the lowest weight.
20947 if (!CallOperandVal)
20948 return CW_Default;
20949 Type *type = CallOperandVal->getType();
20950 // Look at the constraint type.
20951 switch (*constraint) {
20952 default:
20954 break;
20955 case 'l':
20956 if (type->isIntegerTy()) {
20957 if (Subtarget->isThumb())
20959 else
20961 }
20962 break;
20963 case 'w':
20964 if (type->isFloatingPointTy())
20966 break;
20967 }
20968 return weight;
20969}
20970
20971static bool isIncompatibleReg(const MCPhysReg &PR, MVT VT) {
20972 if (PR == 0 || VT == MVT::Other)
20973 return false;
20974 if (ARM::SPRRegClass.contains(PR))
20975 return VT != MVT::f32 && VT != MVT::f16 && VT != MVT::i32;
20976 if (ARM::DPRRegClass.contains(PR))
20977 return VT != MVT::f64 && !VT.is64BitVector();
20978 return false;
20979}
20980
20981using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
20982
20984 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
20985 switch (Constraint.size()) {
20986 case 1:
20987 // GCC ARM Constraint Letters
20988 switch (Constraint[0]) {
20989 case 'l': // Low regs or general regs.
20990 if (Subtarget->isThumb())
20991 return RCPair(0U, &ARM::tGPRRegClass);
20992 return RCPair(0U, &ARM::GPRRegClass);
20993 case 'h': // High regs or no regs.
20994 if (Subtarget->isThumb())
20995 return RCPair(0U, &ARM::hGPRRegClass);
20996 break;
20997 case 'r':
20998 if (Subtarget->isThumb1Only())
20999 return RCPair(0U, &ARM::tGPRRegClass);
21000 return RCPair(0U, &ARM::GPRRegClass);
21001 case 'w':
21002 if (VT == MVT::Other)
21003 break;
21004 if (VT == MVT::f32 || VT == MVT::f16 || VT == MVT::bf16)
21005 return RCPair(0U, &ARM::SPRRegClass);
21006 if (VT.getSizeInBits() == 64)
21007 return RCPair(0U, &ARM::DPRRegClass);
21008 if (VT.getSizeInBits() == 128)
21009 return RCPair(0U, &ARM::QPRRegClass);
21010 break;
21011 case 'x':
21012 if (VT == MVT::Other)
21013 break;
21014 if (VT == MVT::f32 || VT == MVT::f16 || VT == MVT::bf16)
21015 return RCPair(0U, &ARM::SPR_8RegClass);
21016 if (VT.getSizeInBits() == 64)
21017 return RCPair(0U, &ARM::DPR_8RegClass);
21018 if (VT.getSizeInBits() == 128)
21019 return RCPair(0U, &ARM::QPR_8RegClass);
21020 break;
21021 case 't':
21022 if (VT == MVT::Other)
21023 break;
21024 if (VT == MVT::f32 || VT == MVT::i32 || VT == MVT::f16 || VT == MVT::bf16)
21025 return RCPair(0U, &ARM::SPRRegClass);
21026 if (VT.getSizeInBits() == 64)
21027 return RCPair(0U, &ARM::DPR_VFP2RegClass);
21028 if (VT.getSizeInBits() == 128)
21029 return RCPair(0U, &ARM::QPR_VFP2RegClass);
21030 break;
21031 }
21032 break;
21033
21034 case 2:
21035 if (Constraint[0] == 'T') {
21036 switch (Constraint[1]) {
21037 default:
21038 break;
21039 case 'e':
21040 return RCPair(0U, &ARM::tGPREvenRegClass);
21041 case 'o':
21042 return RCPair(0U, &ARM::tGPROddRegClass);
21043 }
21044 }
21045 break;
21046
21047 default:
21048 break;
21049 }
21050
21051 if (StringRef("{cc}").equals_insensitive(Constraint))
21052 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
21053
21054 // r14 is an alias of lr.
21055 if (StringRef("{r14}").equals_insensitive(Constraint))
21056 Constraint = "{lr}";
21057
21058 auto RCP = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
21059 if (isIncompatibleReg(RCP.first, VT))
21060 return {0, nullptr};
21061 return RCP;
21062}
21063
21064/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
21065/// vector. If it is invalid, don't add anything to Ops.
21067 StringRef Constraint,
21068 std::vector<SDValue> &Ops,
21069 SelectionDAG &DAG) const {
21070 SDValue Result;
21071
21072 // Currently only support length 1 constraints.
21073 if (Constraint.size() != 1)
21074 return;
21075
21076 char ConstraintLetter = Constraint[0];
21077 switch (ConstraintLetter) {
21078 default: break;
21079 case 'j':
21080 case 'I': case 'J': case 'K': case 'L':
21081 case 'M': case 'N': case 'O':
21083 if (!C)
21084 return;
21085
21086 int64_t CVal64 = C->getSExtValue();
21087 int CVal = (int) CVal64;
21088 // None of these constraints allow values larger than 32 bits. Check
21089 // that the value fits in an int.
21090 if (CVal != CVal64)
21091 return;
21092
21093 switch (ConstraintLetter) {
21094 case 'j':
21095 // Constant suitable for movw, must be between 0 and
21096 // 65535.
21097 if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps()))
21098 if (CVal >= 0 && CVal <= 65535)
21099 break;
21100 return;
21101 case 'I':
21102 if (Subtarget->isThumb1Only()) {
21103 // This must be a constant between 0 and 255, for ADD
21104 // immediates.
21105 if (CVal >= 0 && CVal <= 255)
21106 break;
21107 } else if (Subtarget->isThumb2()) {
21108 // A constant that can be used as an immediate value in a
21109 // data-processing instruction.
21110 if (ARM_AM::getT2SOImmVal(CVal) != -1)
21111 break;
21112 } else {
21113 // A constant that can be used as an immediate value in a
21114 // data-processing instruction.
21115 if (ARM_AM::getSOImmVal(CVal) != -1)
21116 break;
21117 }
21118 return;
21119
21120 case 'J':
21121 if (Subtarget->isThumb1Only()) {
21122 // This must be a constant between -255 and -1, for negated ADD
21123 // immediates. This can be used in GCC with an "n" modifier that
21124 // prints the negated value, for use with SUB instructions. It is
21125 // not useful otherwise but is implemented for compatibility.
21126 if (CVal >= -255 && CVal <= -1)
21127 break;
21128 } else {
21129 // This must be a constant between -4095 and 4095. This is suitable
21130 // for use as the immediate offset field in LDR and STR instructions
21131 // such as LDR r0,[r1,#offset].
21132 if (CVal >= -4095 && CVal <= 4095)
21133 break;
21134 }
21135 return;
21136
21137 case 'K':
21138 if (Subtarget->isThumb1Only()) {
21139 // A 32-bit value where only one byte has a nonzero value. Exclude
21140 // zero to match GCC. This constraint is used by GCC internally for
21141 // constants that can be loaded with a move/shift combination.
21142 // It is not useful otherwise but is implemented for compatibility.
21143 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
21144 break;
21145 } else if (Subtarget->isThumb2()) {
21146 // A constant whose bitwise inverse can be used as an immediate
21147 // value in a data-processing instruction. This can be used in GCC
21148 // with a "B" modifier that prints the inverted value, for use with
21149 // BIC and MVN instructions. It is not useful otherwise but is
21150 // implemented for compatibility.
21151 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
21152 break;
21153 } else {
21154 // A constant whose bitwise inverse can be used as an immediate
21155 // value in a data-processing instruction. This can be used in GCC
21156 // with a "B" modifier that prints the inverted value, for use with
21157 // BIC and MVN instructions. It is not useful otherwise but is
21158 // implemented for compatibility.
21159 if (ARM_AM::getSOImmVal(~CVal) != -1)
21160 break;
21161 }
21162 return;
21163
21164 case 'L':
21165 if (Subtarget->isThumb1Only()) {
21166 // This must be a constant between -7 and 7,
21167 // for 3-operand ADD/SUB immediate instructions.
21168 if (CVal >= -7 && CVal < 7)
21169 break;
21170 } else if (Subtarget->isThumb2()) {
21171 // A constant whose negation can be used as an immediate value in a
21172 // data-processing instruction. This can be used in GCC with an "n"
21173 // modifier that prints the negated value, for use with SUB
21174 // instructions. It is not useful otherwise but is implemented for
21175 // compatibility.
21176 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
21177 break;
21178 } else {
21179 // A constant whose negation can be used as an immediate value in a
21180 // data-processing instruction. This can be used in GCC with an "n"
21181 // modifier that prints the negated value, for use with SUB
21182 // instructions. It is not useful otherwise but is implemented for
21183 // compatibility.
21184 if (ARM_AM::getSOImmVal(-CVal) != -1)
21185 break;
21186 }
21187 return;
21188
21189 case 'M':
21190 if (Subtarget->isThumb1Only()) {
21191 // This must be a multiple of 4 between 0 and 1020, for
21192 // ADD sp + immediate.
21193 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
21194 break;
21195 } else {
21196 // A power of two or a constant between 0 and 32. This is used in
21197 // GCC for the shift amount on shifted register operands, but it is
21198 // useful in general for any shift amounts.
21199 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
21200 break;
21201 }
21202 return;
21203
21204 case 'N':
21205 if (Subtarget->isThumb1Only()) {
21206 // This must be a constant between 0 and 31, for shift amounts.
21207 if (CVal >= 0 && CVal <= 31)
21208 break;
21209 }
21210 return;
21211
21212 case 'O':
21213 if (Subtarget->isThumb1Only()) {
21214 // This must be a multiple of 4 between -508 and 508, for
21215 // ADD/SUB sp = sp + immediate.
21216 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
21217 break;
21218 }
21219 return;
21220 }
21221 Result = DAG.getSignedTargetConstant(CVal, SDLoc(Op), Op.getValueType());
21222 break;
21223 }
21224
21225 if (Result.getNode()) {
21226 Ops.push_back(Result);
21227 return;
21228 }
21229 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21230}
21231
21232static RTLIB::Libcall getDivRemLibcall(
21233 const SDNode *N, MVT::SimpleValueType SVT) {
21234 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
21235 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
21236 "Unhandled Opcode in getDivRemLibcall");
21237 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
21238 N->getOpcode() == ISD::SREM;
21239 RTLIB::Libcall LC;
21240 switch (SVT) {
21241 default: llvm_unreachable("Unexpected request for libcall!");
21242 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
21243 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
21244 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
21245 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
21246 }
21247 return LC;
21248}
21249
21252 const AttributeList &FuncAttrs, RTLIB::LibcallImpl LCImpl) {
21253 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
21254 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
21255 "Unhandled Opcode in getDivRemArgList");
21256 SDValue Ops[2] = {N->getOperand(0), N->getOperand(1)};
21257
21258 // The Windows __rt_*div* helpers take the divisor before the dividend.
21259 switch (LCImpl) {
21260 case RTLIB::impl___rt_sdiv:
21261 case RTLIB::impl___rt_udiv:
21262 case RTLIB::impl___rt_sdiv64:
21263 case RTLIB::impl___rt_udiv64:
21264 std::swap(Ops[0], Ops[1]);
21265 break;
21266 default:
21267 break;
21268 }
21269
21270 return TargetLowering::getArgListForFunctionType(FuncTy, FuncAttrs, Ops);
21271}
21272
21273SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
21274 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
21275 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
21276 Subtarget->isTargetFuchsia() || Subtarget->isTargetWindows()) &&
21277 "Register-based DivRem lowering only");
21278 unsigned Opcode = Op->getOpcode();
21279 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
21280 "Invalid opcode for Div/Rem lowering");
21281 bool isSigned = (Opcode == ISD::SDIVREM);
21282 EVT VT = Op->getValueType(0);
21283 SDLoc dl(Op);
21284
21285 if (VT == MVT::i64 && isa<ConstantSDNode>(Op.getOperand(1))) {
21287 if (expandDIVREMByConstant(Op.getNode(), Result, MVT::i32, DAG)) {
21288 SDValue Res0 =
21289 DAG.getNode(ISD::BUILD_PAIR, dl, VT, Result[0], Result[1]);
21290 SDValue Res1 =
21291 DAG.getNode(ISD::BUILD_PAIR, dl, VT, Result[2], Result[3]);
21292 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
21293 {Res0, Res1});
21294 }
21295 }
21296
21297 // If the target has hardware divide, use divide + multiply + subtract:
21298 // div = a / b
21299 // rem = a - b * div
21300 // return {div, rem}
21301 // This should be lowered into UDIV/SDIV + MLS later on.
21302 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
21303 : Subtarget->hasDivideInARMMode();
21304 if (hasDivide && Op->getValueType(0).isSimple() &&
21305 Op->getSimpleValueType(0) == MVT::i32) {
21306 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
21307 const SDValue Dividend = Op->getOperand(0);
21308 const SDValue Divisor = Op->getOperand(1);
21309 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
21310 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
21311 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
21312
21313 SDValue Values[2] = {Div, Rem};
21314 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
21315 }
21316
21317 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
21318 VT.getSimpleVT().SimpleTy);
21319 RTLIB::LibcallImpl LCImpl = DAG.getLibcalls().getLibcallImpl(LC);
21320 if (LCImpl == RTLIB::Unsupported)
21321 return SDValue();
21322
21323 auto [FuncTy, FuncAttrs] =
21325 *DAG.getContext(), getTM().getTargetTriple(), DAG.getDataLayout(),
21326 LCImpl);
21327 Type *RetTy = FuncTy->getReturnType();
21328
21329 SDValue InChain = DAG.getEntryNode();
21330
21332 getDivRemArgList(Op.getNode(), FuncTy, FuncAttrs, LCImpl);
21333
21334 SDValue Callee =
21335 DAG.getExternalSymbol(LCImpl, getPointerTy(DAG.getDataLayout()));
21336
21337 if (getTM().getTargetTriple().isOSWindows())
21338 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
21339
21340 TargetLowering::CallLoweringInfo CLI(DAG);
21341 CLI.setDebugLoc(dl)
21342 .setChain(InChain)
21343 .setCallee(DAG.getLibcalls().getLibcallImplCallingConv(LCImpl), RetTy,
21344 Callee, std::move(Args))
21345 .setInRegister()
21348
21349 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
21350 return CallInfo.first;
21351}
21352
21353// Lowers REM using divmod helpers
21354// see RTABI section 4.2/4.3
21355SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
21356 EVT VT = N->getValueType(0);
21357
21358 if (VT == MVT::i64 && isa<ConstantSDNode>(N->getOperand(1))) {
21360 if (expandDIVREMByConstant(N, Result, MVT::i32, DAG))
21361 return DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), N->getValueType(0),
21362 Result[0], Result[1]);
21363 }
21364
21365 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
21366 SimpleTy);
21367 RTLIB::LibcallImpl LCImpl = DAG.getLibcalls().getLibcallImpl(LC);
21368 if (LCImpl == RTLIB::Unsupported)
21369 return SDValue();
21370
21371 auto [FuncTy, FuncAttrs] =
21373 *DAG.getContext(), getTM().getTargetTriple(), DAG.getDataLayout(),
21374 LCImpl);
21375 Type *RetTy = FuncTy->getReturnType();
21376
21377 SDValue InChain = DAG.getEntryNode();
21379 getDivRemArgList(N, FuncTy, FuncAttrs, LCImpl);
21380 bool isSigned = N->getOpcode() == ISD::SREM;
21381
21382 SDValue Callee =
21383 DAG.getExternalSymbol(LCImpl, getPointerTy(DAG.getDataLayout()));
21384
21385 if (getTM().getTargetTriple().isOSWindows())
21386 InChain = WinDBZCheckDenominator(DAG, N, InChain);
21387
21388 // Lower call
21389 CallLoweringInfo CLI(DAG);
21390 CLI.setChain(InChain)
21391 .setCallee(DAG.getLibcalls().getLibcallImplCallingConv(LCImpl), RetTy,
21392 Callee, std::move(Args))
21395 .setDebugLoc(SDLoc(N));
21396 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
21397
21398 // Return second (rem) result operand (first contains div)
21399 SDNode *ResNode = CallResult.first.getNode();
21400 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
21401 return ResNode->getOperand(1);
21402}
21403
21404SDValue
21405ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
21406 assert(getTM().getTargetTriple().isOSWindows() &&
21407 "unsupported target platform");
21408 SDLoc DL(Op);
21409
21410 // Get the inputs.
21411 SDValue Chain = Op.getOperand(0);
21412 SDValue Size = Op.getOperand(1);
21413
21415 "no-stack-arg-probe")) {
21416 MaybeAlign Align =
21417 cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
21418 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
21419 Chain = SP.getValue(1);
21420 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
21421 if (Align)
21422 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
21423 DAG.getSignedConstant(-Align->value(), DL, MVT::i32));
21424 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
21425 SDValue Ops[2] = { SP, Chain };
21426 return DAG.getMergeValues(Ops, DL);
21427 }
21428
21429 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
21430 DAG.getConstant(2, DL, MVT::i32));
21431
21432 SDValue Glue;
21433 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Glue);
21434 Glue = Chain.getValue(1);
21435
21436 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
21437 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Glue);
21438
21439 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
21440 Chain = NewSP.getValue(1);
21441
21442 SDValue Ops[2] = { NewSP, Chain };
21443 return DAG.getMergeValues(Ops, DL);
21444}
21445
21446SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
21447 bool IsStrict = Op->isStrictFPOpcode();
21448 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
21449 EVT DstTy = Op.getValueType();
21450 const unsigned DstSz = DstTy.getSizeInBits();
21451 EVT SrcTy = SrcVal.getValueType();
21452 const unsigned SrcSz = SrcTy.getSizeInBits();
21453 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
21454 "Unexpected type for custom-lowering FP_EXTEND");
21455
21456 // f16->f32 is legal with hasFP16
21457 if (DstTy == MVT::f32 && SrcTy == MVT::f16 && Subtarget->hasFP16())
21458 return Op;
21459 // f16->f64 is legal with hasFP16 and hasFP64
21460 if (DstTy == MVT::f64 && SrcTy == MVT::f16 && Subtarget->hasFP16() &&
21461 Subtarget->hasFP64() && Subtarget->hasFPARMv8Base())
21462 return Op;
21463
21464 // Expand any bf16 ops into a shift and a possible further extend
21465 if (SrcTy == MVT::bf16) {
21466 SDLoc DL(Op);
21467 SDValue Mov = DAG.getNode(ARMISD::VMOVrs, DL, MVT::i32, SrcVal);
21468 SDValue Shft = DAG.getNode(ISD::SHL, DL, MVT::i32, Mov,
21469 DAG.getConstant(16, DL, MVT::i32));
21470 SDValue Res = DAG.getBitcast(MVT::f32, Shft);
21471 if (DstTy == MVT::f32)
21472 return IsStrict ? DAG.getMergeValues({Res, Op.getOperand(0)}, DL) : Res;
21473
21474 assert(DstTy == MVT::f64 && "Unexpected BF16 convert");
21475 if (IsStrict)
21476 return DAG.getNode(ISD::STRICT_FP_EXTEND, DL, {DstTy, MVT::Other},
21477 {Op.getOperand(0), Res});
21478 return DAG.getNode(ISD::FP_EXTEND, DL, DstTy, Res);
21479 }
21480
21481 // Converting from 32 -> 64 is valid if we have FP64.
21482 if (SrcTy == MVT::f32 && DstTy == MVT::f64 && Subtarget->hasFP64()) {
21483 // FIXME: Remove this when we have strict fp instruction selection patterns
21484 if (IsStrict) {
21485 SDLoc Loc(Op);
21486 SDValue Result = DAG.getNode(ISD::FP_EXTEND, Loc, DstTy, SrcVal);
21487 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
21488 }
21489 return Op;
21490 }
21491
21492 // Either we are converting from 16 -> 64, without FP16 and/or
21493 // FP.double-precision or without Armv8-fp. So we must do it in two
21494 // steps.
21495 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
21496 // without FP16. So we must do a function call.
21497 SDLoc Loc(Op);
21498 RTLIB::Libcall LC;
21499 MakeLibCallOptions CallOptions;
21500 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
21501 for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) {
21502 bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64());
21503 MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32);
21504 MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64);
21505 if (Supported) {
21506 if (IsStrict) {
21507 SrcVal = DAG.getNode(ISD::STRICT_FP_EXTEND, Loc,
21508 {DstVT, MVT::Other}, {Chain, SrcVal});
21509 Chain = SrcVal.getValue(1);
21510 } else {
21511 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, DstVT, SrcVal);
21512 }
21513 } else {
21514 LC = RTLIB::getFPEXT(SrcVT, DstVT);
21515 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
21516 "Unexpected type for custom-lowering FP_EXTEND");
21517 std::tie(SrcVal, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
21518 Loc, Chain);
21519 }
21520 }
21521
21522 return IsStrict ? DAG.getMergeValues({SrcVal, Chain}, Loc) : SrcVal;
21523}
21524
21525SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
21526 bool IsStrict = Op->isStrictFPOpcode();
21527
21528 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
21529 EVT SrcVT = SrcVal.getValueType();
21530 EVT DstVT = Op.getValueType();
21531
21532 if (DstVT == MVT::bf16) {
21533 if (Subtarget->hasBF16() && SrcVT == MVT::f32)
21534 return Op;
21535 return SDValue();
21536 }
21537
21538 const unsigned DstSz = Op.getValueType().getSizeInBits();
21539 const unsigned SrcSz = SrcVT.getSizeInBits();
21540 (void)DstSz;
21541 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
21542 "Unexpected type for custom-lowering FP_ROUND");
21543
21544 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
21545 "With both FP DP and 16, any FP conversion is legal!");
21546
21547 SDLoc Loc(Op);
21548
21549 // Instruction from 32 -> 16 if hasFP16 is valid
21550 if (SrcSz == 32 && Subtarget->hasFP16())
21551 return Op;
21552
21553 // Lib call from 32 -> 16 / 64 -> [32, 16]
21554 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
21555 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
21556 "Unexpected type for custom-lowering FP_ROUND");
21557 MakeLibCallOptions CallOptions;
21558 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
21560 std::tie(Result, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
21561 Loc, Chain);
21562 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
21563}
21564
21565bool
21567 // The ARM target isn't yet aware of offsets.
21568 return false;
21569}
21570
21572 if (v == 0xffffffff)
21573 return false;
21574
21575 // there can be 1's on either or both "outsides", all the "inside"
21576 // bits must be 0's
21577 return isShiftedMask_32(~v);
21578}
21579
21580/// Returns how to materialize the specified FP immediate.
21583 bool ForCodeSize) const {
21584 if (!Subtarget->hasVFP3Base())
21586 if (VT == MVT::f16 && Subtarget->hasFullFP16())
21589 if (VT == MVT::f32 && Subtarget->hasFullFP16() &&
21591 return FPImmAction::Legal;
21592 if (VT == MVT::f32)
21595 if (VT == MVT::f64 && Subtarget->hasFP64())
21599}
21600
21603 bool ForCodeSize) const {
21604 if (Subtarget->useSoftFloat() || !Subtarget->hasVFP2Base())
21605 return FPImmAction::Bitcast;
21607}
21608
21609/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
21610/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
21611/// specified in the intrinsic calls.
21614 MachineFunction &MF, unsigned Intrinsic) const {
21615 IntrinsicInfo Info;
21616 switch (Intrinsic) {
21617 case Intrinsic::arm_neon_vld1:
21618 case Intrinsic::arm_neon_vld2:
21619 case Intrinsic::arm_neon_vld3:
21620 case Intrinsic::arm_neon_vld4:
21621 case Intrinsic::arm_neon_vld2lane:
21622 case Intrinsic::arm_neon_vld3lane:
21623 case Intrinsic::arm_neon_vld4lane:
21624 case Intrinsic::arm_neon_vld2dup:
21625 case Intrinsic::arm_neon_vld3dup:
21626 case Intrinsic::arm_neon_vld4dup: {
21627 Info.opc = ISD::INTRINSIC_W_CHAIN;
21628 // Conservatively set memVT to the entire set of vectors loaded.
21629 auto &DL = I.getDataLayout();
21630 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
21631 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
21632 Info.ptrVal = I.getArgOperand(0);
21633 Info.offset = 0;
21634 Value *AlignArg = I.getArgOperand(I.arg_size() - 1);
21635 Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue();
21636 // volatile loads with NEON intrinsics not supported
21637 Info.flags = MachineMemOperand::MOLoad;
21638 Infos.push_back(Info);
21639 return;
21640 }
21641 case Intrinsic::arm_neon_vld1x2:
21642 case Intrinsic::arm_neon_vld1x3:
21643 case Intrinsic::arm_neon_vld1x4: {
21644 Info.opc = ISD::INTRINSIC_W_CHAIN;
21645 // Conservatively set memVT to the entire set of vectors loaded.
21646 auto &DL = I.getDataLayout();
21647 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
21648 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
21649 Info.ptrVal = I.getArgOperand(I.arg_size() - 1);
21650 Info.offset = 0;
21651 Info.align = I.getParamAlign(I.arg_size() - 1).valueOrOne();
21652 // volatile loads with NEON intrinsics not supported
21653 Info.flags = MachineMemOperand::MOLoad;
21654 Infos.push_back(Info);
21655 return;
21656 }
21657 case Intrinsic::arm_neon_vst1:
21658 case Intrinsic::arm_neon_vst2:
21659 case Intrinsic::arm_neon_vst3:
21660 case Intrinsic::arm_neon_vst4:
21661 case Intrinsic::arm_neon_vst2lane:
21662 case Intrinsic::arm_neon_vst3lane:
21663 case Intrinsic::arm_neon_vst4lane: {
21664 Info.opc = ISD::INTRINSIC_VOID;
21665 // Conservatively set memVT to the entire set of vectors stored.
21666 auto &DL = I.getDataLayout();
21667 unsigned NumElts = 0;
21668 for (unsigned ArgI = 1, ArgE = I.arg_size(); ArgI < ArgE; ++ArgI) {
21669 Type *ArgTy = I.getArgOperand(ArgI)->getType();
21670 if (!ArgTy->isVectorTy())
21671 break;
21672 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
21673 }
21674 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
21675 Info.ptrVal = I.getArgOperand(0);
21676 Info.offset = 0;
21677 Value *AlignArg = I.getArgOperand(I.arg_size() - 1);
21678 Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue();
21679 // volatile stores with NEON intrinsics not supported
21680 Info.flags = MachineMemOperand::MOStore;
21681 Infos.push_back(Info);
21682 return;
21683 }
21684 case Intrinsic::arm_neon_vst1x2:
21685 case Intrinsic::arm_neon_vst1x3:
21686 case Intrinsic::arm_neon_vst1x4: {
21687 Info.opc = ISD::INTRINSIC_VOID;
21688 // Conservatively set memVT to the entire set of vectors stored.
21689 auto &DL = I.getDataLayout();
21690 unsigned NumElts = 0;
21691 for (unsigned ArgI = 1, ArgE = I.arg_size(); ArgI < ArgE; ++ArgI) {
21692 Type *ArgTy = I.getArgOperand(ArgI)->getType();
21693 if (!ArgTy->isVectorTy())
21694 break;
21695 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
21696 }
21697 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
21698 Info.ptrVal = I.getArgOperand(0);
21699 Info.offset = 0;
21700 Info.align = I.getParamAlign(0).valueOrOne();
21701 // volatile stores with NEON intrinsics not supported
21702 Info.flags = MachineMemOperand::MOStore;
21703 Infos.push_back(Info);
21704 return;
21705 }
21706 case Intrinsic::arm_mve_vld2q:
21707 case Intrinsic::arm_mve_vld4q: {
21708 Info.opc = ISD::INTRINSIC_W_CHAIN;
21709 // Conservatively set memVT to the entire set of vectors loaded.
21710 Type *VecTy = cast<StructType>(I.getType())->getElementType(1);
21711 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vld2q ? 2 : 4;
21712 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
21713 Info.ptrVal = I.getArgOperand(0);
21714 Info.offset = 0;
21715 Info.align = Align(VecTy->getScalarSizeInBits() / 8);
21716 // volatile loads with MVE intrinsics not supported
21717 Info.flags = MachineMemOperand::MOLoad;
21718 Infos.push_back(Info);
21719 return;
21720 }
21721 case Intrinsic::arm_mve_vst2q:
21722 case Intrinsic::arm_mve_vst4q: {
21723 Info.opc = ISD::INTRINSIC_VOID;
21724 // Conservatively set memVT to the entire set of vectors stored.
21725 Type *VecTy = I.getArgOperand(1)->getType();
21726 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vst2q ? 2 : 4;
21727 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
21728 Info.ptrVal = I.getArgOperand(0);
21729 Info.offset = 0;
21730 Info.align = Align(VecTy->getScalarSizeInBits() / 8);
21731 // volatile stores with MVE intrinsics not supported
21732 Info.flags = MachineMemOperand::MOStore;
21733 Infos.push_back(Info);
21734 return;
21735 }
21736 case Intrinsic::arm_mve_vldr_gather_base:
21737 case Intrinsic::arm_mve_vldr_gather_base_predicated: {
21738 Info.opc = ISD::INTRINSIC_W_CHAIN;
21739 Info.ptrVal = nullptr;
21740 Info.memVT = MVT::getVT(I.getType());
21741 Info.align = Align(1);
21742 Info.flags |= MachineMemOperand::MOLoad;
21743 Infos.push_back(Info);
21744 return;
21745 }
21746 case Intrinsic::arm_mve_vldr_gather_base_wb:
21747 case Intrinsic::arm_mve_vldr_gather_base_wb_predicated: {
21748 Info.opc = ISD::INTRINSIC_W_CHAIN;
21749 Info.ptrVal = nullptr;
21750 Info.memVT = MVT::getVT(I.getType()->getContainedType(0));
21751 Info.align = Align(1);
21752 Info.flags |= MachineMemOperand::MOLoad;
21753 Infos.push_back(Info);
21754 return;
21755 }
21756 case Intrinsic::arm_mve_vldr_gather_offset:
21757 case Intrinsic::arm_mve_vldr_gather_offset_predicated: {
21758 Info.opc = ISD::INTRINSIC_W_CHAIN;
21759 Info.ptrVal = nullptr;
21760 MVT DataVT = MVT::getVT(I.getType());
21761 unsigned MemSize = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
21762 Info.memVT = MVT::getVectorVT(MVT::getIntegerVT(MemSize),
21763 DataVT.getVectorNumElements());
21764 Info.align = Align(1);
21765 Info.flags |= MachineMemOperand::MOLoad;
21766 Infos.push_back(Info);
21767 return;
21768 }
21769 case Intrinsic::arm_mve_vstr_scatter_base:
21770 case Intrinsic::arm_mve_vstr_scatter_base_predicated: {
21771 Info.opc = ISD::INTRINSIC_VOID;
21772 Info.ptrVal = nullptr;
21773 Info.memVT = MVT::getVT(I.getArgOperand(2)->getType());
21774 Info.align = Align(1);
21775 Info.flags |= MachineMemOperand::MOStore;
21776 Infos.push_back(Info);
21777 return;
21778 }
21779 case Intrinsic::arm_mve_vstr_scatter_base_wb:
21780 case Intrinsic::arm_mve_vstr_scatter_base_wb_predicated: {
21781 Info.opc = ISD::INTRINSIC_W_CHAIN;
21782 Info.ptrVal = nullptr;
21783 Info.memVT = MVT::getVT(I.getArgOperand(2)->getType());
21784 Info.align = Align(1);
21785 Info.flags |= MachineMemOperand::MOStore;
21786 Infos.push_back(Info);
21787 return;
21788 }
21789 case Intrinsic::arm_mve_vstr_scatter_offset:
21790 case Intrinsic::arm_mve_vstr_scatter_offset_predicated: {
21791 Info.opc = ISD::INTRINSIC_VOID;
21792 Info.ptrVal = nullptr;
21793 MVT DataVT = MVT::getVT(I.getArgOperand(2)->getType());
21794 unsigned MemSize = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
21795 Info.memVT = MVT::getVectorVT(MVT::getIntegerVT(MemSize),
21796 DataVT.getVectorNumElements());
21797 Info.align = Align(1);
21798 Info.flags |= MachineMemOperand::MOStore;
21799 Infos.push_back(Info);
21800 return;
21801 }
21802 case Intrinsic::arm_ldaex:
21803 case Intrinsic::arm_ldrex: {
21804 auto &DL = I.getDataLayout();
21805 Type *ValTy = I.getParamElementType(0);
21806 Info.opc = ISD::INTRINSIC_W_CHAIN;
21807 Info.memVT = MVT::getVT(ValTy);
21808 Info.ptrVal = I.getArgOperand(0);
21809 Info.offset = 0;
21810 Info.align = DL.getABITypeAlign(ValTy);
21812 Infos.push_back(Info);
21813 return;
21814 }
21815 case Intrinsic::arm_stlex:
21816 case Intrinsic::arm_strex: {
21817 auto &DL = I.getDataLayout();
21818 Type *ValTy = I.getParamElementType(1);
21819 Info.opc = ISD::INTRINSIC_W_CHAIN;
21820 Info.memVT = MVT::getVT(ValTy);
21821 Info.ptrVal = I.getArgOperand(1);
21822 Info.offset = 0;
21823 Info.align = DL.getABITypeAlign(ValTy);
21825 Infos.push_back(Info);
21826 return;
21827 }
21828 case Intrinsic::arm_stlexd:
21829 case Intrinsic::arm_strexd:
21830 Info.opc = ISD::INTRINSIC_W_CHAIN;
21831 Info.memVT = MVT::i64;
21832 Info.ptrVal = I.getArgOperand(2);
21833 Info.offset = 0;
21834 Info.align = Align(8);
21836 Infos.push_back(Info);
21837 return;
21838
21839 case Intrinsic::arm_ldaexd:
21840 case Intrinsic::arm_ldrexd:
21841 Info.opc = ISD::INTRINSIC_W_CHAIN;
21842 Info.memVT = MVT::i64;
21843 Info.ptrVal = I.getArgOperand(0);
21844 Info.offset = 0;
21845 Info.align = Align(8);
21847 Infos.push_back(Info);
21848 return;
21849
21850 default:
21851 break;
21852 }
21853}
21854
21855/// Returns true if it is beneficial to convert a load of a constant
21856/// to just the constant itself.
21858 Type *Ty) const {
21859 assert(Ty->isIntegerTy());
21860
21861 unsigned Bits = Ty->getPrimitiveSizeInBits();
21862 if (Bits == 0 || Bits > 32)
21863 return false;
21864 return true;
21865}
21866
21869 unsigned Index) const {
21872
21873 if (Index == 0 || Index == ResVT.getVectorNumElements())
21876}
21877
21879 ARM_MB::MemBOpt Domain) const {
21880 // First, if the target has no DMB, see what fallback we can use.
21881 if (!Subtarget->hasDataBarrier()) {
21882 // Some ARMv6 cpus can support data barriers with an mcr instruction.
21883 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
21884 // here.
21885 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
21886 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
21887 Builder.getInt32(0), Builder.getInt32(7),
21888 Builder.getInt32(10), Builder.getInt32(5)};
21889 return Builder.CreateIntrinsicWithoutFolding(Intrinsic::arm_mcr, args);
21890 }
21891 // Instead of using barriers, atomic accesses on these subtargets use
21892 // libcalls.
21893 llvm_unreachable("makeDMB on a target so old that it has no barriers");
21894 } else {
21895 // Only a full system barrier exists in the M-class architectures.
21896 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
21897 Constant *CDomain = Builder.getInt32(Domain);
21898 return Builder.CreateIntrinsicWithoutFolding(Intrinsic::arm_dmb, CDomain);
21899 }
21900}
21901
21902// Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
21904 Instruction *Inst,
21905 AtomicOrdering Ord) const {
21906 switch (Ord) {
21909 llvm_unreachable("Invalid fence: unordered/non-atomic");
21912 return nullptr; // Nothing to do
21914 if (!Inst->hasAtomicStore())
21915 return nullptr; // Nothing to do
21916 [[fallthrough]];
21919 if (Subtarget->preferISHSTBarriers())
21920 return makeDMB(Builder, ARM_MB::ISHST);
21921 // FIXME: add a comment with a link to documentation justifying this.
21922 else
21923 return makeDMB(Builder, ARM_MB::ISH);
21924 }
21925 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
21926}
21927
21929 Instruction *Inst,
21930 AtomicOrdering Ord) const {
21931 switch (Ord) {
21934 llvm_unreachable("Invalid fence: unordered/not-atomic");
21937 return nullptr; // Nothing to do
21941 return makeDMB(Builder, ARM_MB::ISH);
21942 }
21943 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
21944}
21945
21946// Loads and stores less than 64-bits are already atomic; ones above that
21947// are doomed anyway, so defer to the default libcall and blame the OS when
21948// things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
21949// anything for those.
21952 bool has64BitLLSC;
21953 if (Subtarget->isMClass())
21954 has64BitLLSC = false;
21955 else if (Subtarget->isThumb())
21956 has64BitLLSC = Subtarget->hasV7Ops();
21957 else
21958 has64BitLLSC = Subtarget->hasV6Ops();
21959
21960 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
21961 if (Size == 64 && has64BitLLSC)
21963
21964 if (Size <= 32 && !hasNativeAtomics(*Subtarget) && !InsertFencesForAtomic &&
21965 isReleaseOrStronger(SI->getOrdering()))
21967
21969}
21970
21971// Loads and stores less than 64-bits are already atomic; ones above that
21972// are doomed anyway, so defer to the default libcall and blame the OS when
21973// things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
21974// anything for those.
21975// FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
21976// guarantee, see DDI0406C ARM architecture reference manual,
21977// sections A8.8.72-74 LDRD)
21980 bool has64BitLLSC;
21981 if (Subtarget->isMClass())
21982 has64BitLLSC = false;
21983 else if (Subtarget->isThumb())
21984 has64BitLLSC = Subtarget->hasV7Ops();
21985 else
21986 has64BitLLSC = Subtarget->hasV6Ops();
21987
21988 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
21989 if (Size == 64 && has64BitLLSC)
21991
21992 if (Size <= 32 && !hasNativeAtomics(*Subtarget) && !InsertFencesForAtomic &&
21995
21997}
21998
21999// For the real atomic operations, we have ldrex/strex up to 32 bits,
22000// and up to 64 bits on the non-M profiles
22003 if (AI->isFloatingPointOperation())
22005
22006 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
22007 bool hasAtomicRMW;
22008 if (Subtarget->isMClass())
22009 hasAtomicRMW = Subtarget->hasV8MBaselineOps();
22010 else if (Subtarget->isThumb())
22011 hasAtomicRMW = Subtarget->hasV7Ops();
22012 else
22013 hasAtomicRMW = Subtarget->hasV6Ops();
22014 if (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) {
22015 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
22016 // implement atomicrmw without spilling. If the target address is also on
22017 // the stack and close enough to the spill slot, this can lead to a
22018 // situation where the monitor always gets cleared and the atomic operation
22019 // can never succeed. So at -O0 lower this operation to a CAS loop.
22020 if (getTargetMachine().getOptLevel() == CodeGenOptLevel::None)
22023 }
22025}
22026
22027// Similar to shouldExpandAtomicRMWInIR, ldrex/strex can be used up to 32
22028// bits, and up to 64 bits on the non-M profiles.
22031 const AtomicCmpXchgInst *AI) const {
22032 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
22033 // implement cmpxchg without spilling. If the address being exchanged is also
22034 // on the stack and close enough to the spill slot, this can lead to a
22035 // situation where the monitor always gets cleared and the atomic operation
22036 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
22037 unsigned Size = AI->getOperand(1)->getType()->getPrimitiveSizeInBits();
22038 bool HasAtomicCmpXchg;
22039 if (Subtarget->isMClass())
22040 HasAtomicCmpXchg = Subtarget->hasV8MBaselineOps();
22041 else if (Subtarget->isThumb())
22042 HasAtomicCmpXchg = Subtarget->hasV7Ops();
22043 else
22044 HasAtomicCmpXchg = Subtarget->hasV6Ops();
22045 if (getTargetMachine().getOptLevel() != CodeGenOptLevel::None &&
22046 HasAtomicCmpXchg && Size <= (Subtarget->isMClass() ? 32U : 64U))
22049}
22050
22052 const Instruction *I) const {
22053 return InsertFencesForAtomic;
22054}
22055
22057 if (Subtarget->isTargetFuchsia())
22059 // ROPI/RWPI are not supported currently.
22060 return !Subtarget->isROPI() && !Subtarget->isRWPI();
22061}
22062
22063Value *
22065 const LibcallLoweringInfo &Libcalls) const {
22066 // Fuchsia provides a fixed TLS slot for the stack cookie.
22067 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
22068 if (Subtarget->isTargetFuchsia()) {
22069 Module *M = IRB.getModule();
22070 Function *ThreadPointerFunc = Intrinsic::getOrInsertDeclaration(
22071 M, Intrinsic::thread_pointer, IRB.getPtrTy());
22072 return IRB.CreateConstGEP1_32(IRB.getInt8Ty(),
22073 IRB.CreateCall(ThreadPointerFunc), -0x10);
22074 }
22075
22076 return TargetLowering::getIRStackGuard(IRB, Libcalls);
22077}
22078
22080 Module &M, const LibcallLoweringInfo &Libcalls) const {
22081 // MSVC CRT provides functionalities for stack protection.
22082 RTLIB::LibcallImpl SecurityCheckCookieLibcall =
22083 Libcalls.getLibcallImpl(RTLIB::SECURITY_CHECK_COOKIE);
22084
22085 RTLIB::LibcallImpl SecurityCookieVar =
22086 Libcalls.getLibcallImpl(RTLIB::STACK_CHECK_GUARD);
22087 if (SecurityCheckCookieLibcall != RTLIB::Unsupported &&
22088 SecurityCookieVar != RTLIB::Unsupported) {
22089 // MSVC CRT has a global variable holding security cookie.
22090 const RTLIB::RuntimeLibcallsInfo &RTLCI = Libcalls.getRuntimeLibcallsInfo();
22091 RTLCI.getOrInsertImplGlobal(M, SecurityCookieVar);
22092
22093 // MSVC CRT has a function to validate security cookie.
22094 FunctionCallee SecurityCheckCookie =
22095 RTLCI.getOrInsertLibcallDecl(M, SecurityCheckCookieLibcall);
22096 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
22097 F->addParamAttr(0, Attribute::AttrKind::InReg);
22098 }
22099
22101}
22102
22104 unsigned &Cost) const {
22105 // If we do not have NEON, vector types are not natively supported.
22106 if (!Subtarget->hasNEON())
22107 return false;
22108
22109 // Floating point values and vector values map to the same register file.
22110 // Therefore, although we could do a store extract of a vector type, this is
22111 // better to leave at float as we have more freedom in the addressing mode for
22112 // those.
22113 if (VectorTy->isFPOrFPVectorTy())
22114 return false;
22115
22116 // If the index is unknown at compile time, this is very expensive to lower
22117 // and it is not possible to combine the store with the extract.
22118 if (!isa<ConstantInt>(Idx))
22119 return false;
22120
22121 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
22122 unsigned BitWidth = VectorTy->getPrimitiveSizeInBits().getFixedValue();
22123 // We can do a store + vector extract on any vector that fits perfectly in a D
22124 // or Q register.
22125 if (BitWidth == 64 || BitWidth == 128) {
22126 Cost = 0;
22127 return true;
22128 }
22129 return false;
22130}
22131
22133 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
22134 UndefPoisonKind Kind, bool ConsiderFlags, unsigned Depth) const {
22135 unsigned Opcode = Op.getOpcode();
22136 switch (Opcode) {
22137 case ARMISD::VORRIMM:
22138 case ARMISD::VBICIMM:
22139 return false;
22140 }
22142 Op, DemandedElts, DAG, Kind, ConsiderFlags, Depth);
22143}
22144
22146 return Subtarget->hasV5TOps() && !Subtarget->isThumb1Only();
22147}
22148
22150 return Subtarget->hasV5TOps() && !Subtarget->isThumb1Only();
22151}
22152
22154 const Instruction &AndI) const {
22155 if (!Subtarget->hasV7Ops())
22156 return false;
22157
22158 // Sink the `and` instruction only if the mask would fit into a modified
22159 // immediate operand.
22161 if (!Mask || Mask->getValue().getBitWidth() > 32u)
22162 return false;
22163 auto MaskVal = unsigned(Mask->getValue().getZExtValue());
22164 return (Subtarget->isThumb2() ? ARM_AM::getT2SOImmVal(MaskVal)
22165 : ARM_AM::getSOImmVal(MaskVal)) != -1;
22166}
22167
22170 SelectionDAG &DAG, SDNode *N, unsigned ExpansionFactor) const {
22171 if (Subtarget->hasMinSize() && !getTM().getTargetTriple().isOSWindows())
22174 ExpansionFactor);
22175}
22176
22178 Value *Addr,
22179 AtomicOrdering Ord) const {
22180 Module *M = Builder.getModule();
22181 bool IsAcquire = isAcquireOrStronger(Ord);
22182
22183 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
22184 // intrinsic must return {i32, i32} and we have to recombine them into a
22185 // single i64 here.
22186 if (ValueTy->getPrimitiveSizeInBits() == 64) {
22188 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
22189
22190 Value *LoHi =
22191 Builder.CreateIntrinsic(Int, Addr, /*FMFSource=*/nullptr, "lohi");
22192
22193 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
22194 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
22195 if (!Subtarget->isLittle())
22196 std::swap (Lo, Hi);
22197 Lo = Builder.CreateZExt(Lo, ValueTy, "lo64");
22198 Hi = Builder.CreateZExt(Hi, ValueTy, "hi64");
22199 return Builder.CreateOr(
22200 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValueTy, 32)), "val64");
22201 }
22202
22203 Type *Tys[] = { Addr->getType() };
22204 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
22205 CallInst *CI = Builder.CreateIntrinsicWithoutFolding(Int, Tys, Addr);
22206
22207 CI->addParamAttr(
22208 0, Attribute::get(M->getContext(), Attribute::ElementType, ValueTy));
22209 return Builder.CreateTruncOrBitCast(CI, ValueTy);
22210}
22211
22213 IRBuilderBase &Builder) const {
22214 if (!(Subtarget->isThumb() ? Subtarget->hasV7Clrex()
22215 : Subtarget->hasV6KOps()))
22216 return;
22217 Builder.CreateIntrinsic(Intrinsic::arm_clrex, {});
22218}
22219
22221 Value *Val, Value *Addr,
22222 AtomicOrdering Ord) const {
22223 Module *M = Builder.getModule();
22224 bool IsRelease = isReleaseOrStronger(Ord);
22225
22226 // Since the intrinsics must have legal type, the i64 intrinsics take two
22227 // parameters: "i32, i32". We must marshal Val into the appropriate form
22228 // before the call.
22229 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
22231 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
22232 Type *Int32Ty = Type::getInt32Ty(M->getContext());
22233
22234 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
22235 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
22236 if (!Subtarget->isLittle())
22237 std::swap(Lo, Hi);
22238 return Builder.CreateIntrinsic(Int, {Lo, Hi, Addr});
22239 }
22240
22241 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
22242 Type *Tys[] = { Addr->getType() };
22244
22245 CallInst *CI = Builder.CreateCall(
22246 Strex, {Builder.CreateZExtOrBitCast(
22247 Val, Strex->getFunctionType()->getParamType(0)),
22248 Addr});
22249 CI->addParamAttr(1, Attribute::get(M->getContext(), Attribute::ElementType,
22250 Val->getType()));
22251 return CI;
22252}
22253
22254
22256 return Subtarget->isMClass();
22257}
22258
22259/// A helper function for determining the number of interleaved accesses we
22260/// will generate when lowering accesses of the given type.
22261unsigned
22263 const DataLayout &DL) const {
22264 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
22265}
22266
22268 unsigned Factor, FixedVectorType *VecTy, Align Alignment,
22269 const DataLayout &DL) const {
22270
22271 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
22272 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
22273
22274 if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps())
22275 return false;
22276
22277 // Ensure the vector doesn't have f16 elements. Even though we could do an
22278 // i16 vldN, we can't hold the f16 vectors and will end up converting via
22279 // f32.
22280 if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy())
22281 return false;
22282 if (Subtarget->hasMVEIntegerOps() && Factor == 3)
22283 return false;
22284
22285 // Ensure the number of vector elements is greater than 1.
22286 if (VecTy->getNumElements() < 2)
22287 return false;
22288
22289 // Ensure the element type is legal.
22290 if (ElSize != 8 && ElSize != 16 && ElSize != 32)
22291 return false;
22292 // And the alignment if high enough under MVE.
22293 if (Subtarget->hasMVEIntegerOps() && Alignment < ElSize / 8)
22294 return false;
22295
22296 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
22297 // 128 will be split into multiple interleaved accesses.
22298 if (Subtarget->hasNEON() && VecSize == 64)
22299 return true;
22300 return VecSize % 128 == 0;
22301}
22302
22304 if (Subtarget->hasNEON())
22305 return 4;
22306 if (Subtarget->hasMVEIntegerOps())
22309}
22310
22311/// Lower an interleaved load into a vldN intrinsic.
22312///
22313/// E.g. Lower an interleaved load (Factor = 2):
22314/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
22315/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
22316/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
22317///
22318/// Into:
22319/// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
22320/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
22321/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
22324 ArrayRef<unsigned> Indices, unsigned Factor, const APInt &GapMask) const {
22325 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
22326 "Invalid interleave factor");
22327 assert(!Shuffles.empty() && "Empty shufflevector input");
22328 assert(Shuffles.size() == Indices.size() &&
22329 "Unmatched number of shufflevectors and indices");
22330
22331 auto *LI = dyn_cast<LoadInst>(Load);
22332 if (!LI)
22333 return false;
22334 assert(!Mask && GapMask.popcount() == Factor && "Unexpected mask on a load");
22335
22336 auto *VecTy = cast<FixedVectorType>(Shuffles[0]->getType());
22337 Type *EltTy = VecTy->getElementType();
22338
22339 const DataLayout &DL = LI->getDataLayout();
22340 Align Alignment = LI->getAlign();
22341
22342 // Skip if we do not have NEON and skip illegal vector types. We can
22343 // "legalize" wide vector types into multiple interleaved accesses as long as
22344 // the vector types are divisible by 128.
22345 if (!isLegalInterleavedAccessType(Factor, VecTy, Alignment, DL))
22346 return false;
22347
22348 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
22349
22350 // A pointer vector can not be the return type of the ldN intrinsics. Need to
22351 // load integer vectors first and then convert to pointer vectors.
22352 if (EltTy->isPointerTy())
22353 VecTy = FixedVectorType::get(DL.getIntPtrType(EltTy), VecTy);
22354
22355 IRBuilder<> Builder(LI);
22356 Builder.disableGEPCanonicalization();
22357
22358 // The base address of the load.
22359 Value *BaseAddr = LI->getPointerOperand();
22360
22361 if (NumLoads > 1) {
22362 // If we're going to generate more than one load, reset the sub-vector type
22363 // to something legal.
22364 VecTy = FixedVectorType::get(VecTy->getElementType(),
22365 VecTy->getNumElements() / NumLoads);
22366 }
22367
22368 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
22369
22370 auto createLoadIntrinsic = [&](Value *BaseAddr) {
22371 if (Subtarget->hasNEON()) {
22372 Type *PtrTy = Builder.getPtrTy(LI->getPointerAddressSpace());
22373 Type *Tys[] = {VecTy, PtrTy};
22374 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
22375 Intrinsic::arm_neon_vld3,
22376 Intrinsic::arm_neon_vld4};
22377
22379 Ops.push_back(BaseAddr);
22380 Ops.push_back(Builder.getInt32(LI->getAlign().value()));
22381
22382 return Builder.CreateIntrinsic(LoadInts[Factor - 2], Tys, Ops,
22383 /*FMFSource=*/nullptr, "vldN");
22384 } else {
22385 assert((Factor == 2 || Factor == 4) &&
22386 "expected interleave factor of 2 or 4 for MVE");
22387 Intrinsic::ID LoadInts =
22388 Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q;
22389 Type *PtrTy = Builder.getPtrTy(LI->getPointerAddressSpace());
22390 Type *Tys[] = {VecTy, PtrTy};
22391
22393 Ops.push_back(BaseAddr);
22394 return Builder.CreateIntrinsic(LoadInts, Tys, Ops, /*FMFSource=*/nullptr,
22395 "vldN");
22396 }
22397 };
22398
22399 // Holds sub-vectors extracted from the load intrinsic return values. The
22400 // sub-vectors are associated with the shufflevector instructions they will
22401 // replace.
22403
22404 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
22405 // If we're generating more than one load, compute the base address of
22406 // subsequent loads as an offset from the previous.
22407 if (LoadCount > 0)
22408 BaseAddr = Builder.CreateConstGEP1_32(VecTy->getElementType(), BaseAddr,
22409 VecTy->getNumElements() * Factor);
22410
22411 Value *VldN = createLoadIntrinsic(BaseAddr);
22412
22413 // Replace uses of each shufflevector with the corresponding vector loaded
22414 // by ldN.
22415 for (unsigned i = 0; i < Shuffles.size(); i++) {
22416 ShuffleVectorInst *SV = Shuffles[i];
22417 unsigned Index = Indices[i];
22418
22419 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
22420
22421 // Convert the integer vector to pointer vector if the element is pointer.
22422 if (EltTy->isPointerTy())
22423 SubVec = Builder.CreateIntToPtr(
22424 SubVec,
22425 FixedVectorType::get(SV->getType()->getElementType(), VecTy));
22426
22427 SubVecs[SV].push_back(SubVec);
22428 }
22429 }
22430
22431 // Replace uses of the shufflevector instructions with the sub-vectors
22432 // returned by the load intrinsic. If a shufflevector instruction is
22433 // associated with more than one sub-vector, those sub-vectors will be
22434 // concatenated into a single wide vector.
22435 for (ShuffleVectorInst *SVI : Shuffles) {
22436 auto &SubVec = SubVecs[SVI];
22437 auto *WideVec =
22438 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
22439 SVI->replaceAllUsesWith(WideVec);
22440 }
22441
22442 return true;
22443}
22444
22445/// Lower an interleaved store into a vstN intrinsic.
22446///
22447/// E.g. Lower an interleaved store (Factor = 3):
22448/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
22449/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
22450/// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
22451///
22452/// Into:
22453/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
22454/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
22455/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
22456/// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
22457///
22458/// Note that the new shufflevectors will be removed and we'll only generate one
22459/// vst3 instruction in CodeGen.
22460///
22461/// Example for a more general valid mask (Factor 3). Lower:
22462/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
22463/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
22464/// store <12 x i32> %i.vec, <12 x i32>* %ptr
22465///
22466/// Into:
22467/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
22468/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
22469/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
22470/// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
22472 Value *LaneMask,
22473 ShuffleVectorInst *SVI,
22474 unsigned Factor,
22475 const APInt &GapMask) const {
22476 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
22477 "Invalid interleave factor");
22478 auto *SI = dyn_cast<StoreInst>(Store);
22479 if (!SI)
22480 return false;
22481 assert(!LaneMask && GapMask.popcount() == Factor &&
22482 "Unexpected mask on store");
22483
22484 auto *VecTy = cast<FixedVectorType>(SVI->getType());
22485 assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
22486
22487 unsigned LaneLen = VecTy->getNumElements() / Factor;
22488 Type *EltTy = VecTy->getElementType();
22489 auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
22490
22491 const DataLayout &DL = SI->getDataLayout();
22492 Align Alignment = SI->getAlign();
22493
22494 // Skip if we do not have NEON and skip illegal vector types. We can
22495 // "legalize" wide vector types into multiple interleaved accesses as long as
22496 // the vector types are divisible by 128.
22497 if (!isLegalInterleavedAccessType(Factor, SubVecTy, Alignment, DL))
22498 return false;
22499
22500 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
22501
22502 Value *Op0 = SVI->getOperand(0);
22503 Value *Op1 = SVI->getOperand(1);
22504 IRBuilder<> Builder(SI);
22505 Builder.disableGEPCanonicalization();
22506
22507 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
22508 // vectors to integer vectors.
22509 if (EltTy->isPointerTy()) {
22510 Type *IntTy = DL.getIntPtrType(EltTy);
22511
22512 // Convert to the corresponding integer vector.
22513 auto *IntVecTy =
22515 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
22516 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
22517
22518 SubVecTy = FixedVectorType::get(IntTy, LaneLen);
22519 }
22520
22521 // The base address of the store.
22522 Value *BaseAddr = SI->getPointerOperand();
22523
22524 if (NumStores > 1) {
22525 // If we're going to generate more than one store, reset the lane length
22526 // and sub-vector type to something legal.
22527 LaneLen /= NumStores;
22528 SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
22529 }
22530
22531 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
22532
22533 auto Mask = SVI->getShuffleMask();
22534
22535 auto createStoreIntrinsic = [&](Value *BaseAddr,
22536 SmallVectorImpl<Value *> &Shuffles) {
22537 if (Subtarget->hasNEON()) {
22538 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
22539 Intrinsic::arm_neon_vst3,
22540 Intrinsic::arm_neon_vst4};
22541 Type *PtrTy = Builder.getPtrTy(SI->getPointerAddressSpace());
22542 Type *Tys[] = {PtrTy, SubVecTy};
22543
22545 Ops.push_back(BaseAddr);
22546 append_range(Ops, Shuffles);
22547 Ops.push_back(Builder.getInt32(SI->getAlign().value()));
22548 Builder.CreateIntrinsic(StoreInts[Factor - 2], Tys, Ops);
22549 } else {
22550 assert((Factor == 2 || Factor == 4) &&
22551 "expected interleave factor of 2 or 4 for MVE");
22552 Intrinsic::ID StoreInts =
22553 Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q;
22554 Type *PtrTy = Builder.getPtrTy(SI->getPointerAddressSpace());
22555 Type *Tys[] = {PtrTy, SubVecTy};
22556
22558 Ops.push_back(BaseAddr);
22559 append_range(Ops, Shuffles);
22560 for (unsigned F = 0; F < Factor; F++) {
22561 Ops.push_back(Builder.getInt32(F));
22562 Builder.CreateIntrinsic(StoreInts, Tys, Ops);
22563 Ops.pop_back();
22564 }
22565 }
22566 };
22567
22568 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
22569 // If we generating more than one store, we compute the base address of
22570 // subsequent stores as an offset from the previous.
22571 if (StoreCount > 0)
22572 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
22573 BaseAddr, LaneLen * Factor);
22574
22575 SmallVector<Value *, 4> Shuffles;
22576
22577 // Split the shufflevector operands into sub vectors for the new vstN call.
22578 for (unsigned i = 0; i < Factor; i++) {
22579 unsigned IdxI = StoreCount * LaneLen * Factor + i;
22580 if (Mask[IdxI] >= 0) {
22581 Shuffles.push_back(Builder.CreateShuffleVector(
22582 Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
22583 } else {
22584 unsigned StartMask = 0;
22585 for (unsigned j = 1; j < LaneLen; j++) {
22586 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
22587 if (Mask[IdxJ * Factor + IdxI] >= 0) {
22588 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
22589 break;
22590 }
22591 }
22592 // Note: If all elements in a chunk are undefs, StartMask=0!
22593 // Note: Filling undef gaps with random elements is ok, since
22594 // those elements were being written anyway (with undefs).
22595 // In the case of all undefs we're defaulting to using elems from 0
22596 // Note: StartMask cannot be negative, it's checked in
22597 // isReInterleaveMask
22598 Shuffles.push_back(Builder.CreateShuffleVector(
22599 Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
22600 }
22601 }
22602
22603 createStoreIntrinsic(BaseAddr, Shuffles);
22604 }
22605 return true;
22606}
22607
22615
22617 uint64_t &Members) {
22618 if (auto *ST = dyn_cast<StructType>(Ty)) {
22619 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
22620 uint64_t SubMembers = 0;
22621 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
22622 return false;
22623 Members += SubMembers;
22624 }
22625 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
22626 uint64_t SubMembers = 0;
22627 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
22628 return false;
22629 Members += SubMembers * AT->getNumElements();
22630 } else if (Ty->isFloatTy()) {
22631 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
22632 return false;
22633 Members = 1;
22634 Base = HA_FLOAT;
22635 } else if (Ty->isDoubleTy()) {
22636 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
22637 return false;
22638 Members = 1;
22639 Base = HA_DOUBLE;
22640 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
22641 Members = 1;
22642 switch (Base) {
22643 case HA_FLOAT:
22644 case HA_DOUBLE:
22645 return false;
22646 case HA_VECT64:
22647 return VT->getPrimitiveSizeInBits().getFixedValue() == 64;
22648 case HA_VECT128:
22649 return VT->getPrimitiveSizeInBits().getFixedValue() == 128;
22650 case HA_UNKNOWN:
22651 switch (VT->getPrimitiveSizeInBits().getFixedValue()) {
22652 case 64:
22653 Base = HA_VECT64;
22654 return true;
22655 case 128:
22656 Base = HA_VECT128;
22657 return true;
22658 default:
22659 return false;
22660 }
22661 }
22662 }
22663
22664 return (Members > 0 && Members <= 4);
22665}
22666
22667/// Return the correct alignment for the current calling convention.
22669 Type *ArgTy, const DataLayout &DL) const {
22670 const Align ABITypeAlign = DL.getABITypeAlign(ArgTy);
22671 if (!ArgTy->isVectorTy())
22672 return ABITypeAlign;
22673
22674 // Avoid over-aligning vector parameters. It would require realigning the
22675 // stack and waste space for no real benefit.
22676 MaybeAlign StackAlign = DL.getStackAlignment();
22677 assert(StackAlign && "data layout string is missing stack alignment");
22678 return std::min(ABITypeAlign, *StackAlign);
22679}
22680
22681/// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
22682/// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
22683/// passing according to AAPCS rules.
22685 Type *Ty, CallingConv::ID CallConv, bool isVarArg,
22686 const DataLayout &DL) const {
22687 if (getEffectiveCallingConv(CallConv, isVarArg) !=
22689 return false;
22690
22692 uint64_t Members = 0;
22693 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
22694 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
22695
22696 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
22697 return IsHA || IsIntArray;
22698}
22699
22701 ExceptionHandling EH, const Constant *PersonalityFn) const {
22702 // Platforms which do not use SjLj EH may return values in these registers
22703 // via the personality function.
22704 return EH == ExceptionHandling::SjLj ? Register() : ARM::R0;
22705}
22706
22708 ExceptionHandling EH, const Constant *PersonalityFn) const {
22709 // Platforms which do not use SjLj EH may return values in these registers
22710 // via the personality function.
22711 return EH == ExceptionHandling::SjLj ? Register() : ARM::R1;
22712}
22713
22714void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
22715 // Update IsSplitCSR in ARMFunctionInfo.
22716 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
22717 AFI->setIsSplitCSR(true);
22718}
22719
22720void ARMTargetLowering::insertCopiesSplitCSR(
22721 MachineBasicBlock *Entry,
22722 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
22723 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
22724 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
22725 if (!IStart)
22726 return;
22727
22728 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22729 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
22730 MachineBasicBlock::iterator MBBI = Entry->begin();
22731 for (const MCPhysReg *I = IStart; *I; ++I) {
22732 const TargetRegisterClass *RC = nullptr;
22733 if (ARM::GPRRegClass.contains(*I))
22734 RC = &ARM::GPRRegClass;
22735 else if (ARM::DPRRegClass.contains(*I))
22736 RC = &ARM::DPRRegClass;
22737 else
22738 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
22739
22740 Register NewVR = MRI->createVirtualRegister(RC);
22741 // Create copy from CSR to a virtual register.
22742 // FIXME: this currently does not emit CFI pseudo-instructions, it works
22743 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
22744 // nounwind. If we want to generalize this later, we may need to emit
22745 // CFI pseudo-instructions.
22746 assert(Entry->getParent()->getFunction().hasFnAttribute(
22747 Attribute::NoUnwind) &&
22748 "Function should be nounwind in insertCopiesSplitCSR!");
22749 Entry->addLiveIn(*I);
22750 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
22751 .addReg(*I);
22752
22753 // Insert the copy-back instructions right before the terminator.
22754 for (auto *Exit : Exits)
22755 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
22756 TII->get(TargetOpcode::COPY), *I)
22757 .addReg(NewVR);
22758 }
22759}
22760
22765
22767 return Subtarget->hasMVEIntegerOps();
22768}
22769
22771 ComplexDeinterleavingOperation Operation, Type *Ty) const {
22772 auto *VTy = dyn_cast<FixedVectorType>(Ty);
22773 if (!VTy)
22774 return false;
22775
22776 auto *ScalarTy = VTy->getScalarType();
22777 unsigned NumElements = VTy->getNumElements();
22778
22779 unsigned VTyWidth = VTy->getScalarSizeInBits() * NumElements;
22780 if (VTyWidth < 128 || !llvm::isPowerOf2_32(VTyWidth))
22781 return false;
22782
22783 // Both VCADD and VCMUL/VCMLA support the same types, F16 and F32
22784 if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy())
22785 return Subtarget->hasMVEFloatOps();
22786
22787 if (Operation != ComplexDeinterleavingOperation::CAdd)
22788 return false;
22789
22790 return Subtarget->hasMVEIntegerOps() &&
22791 (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
22792 ScalarTy->isIntegerTy(32));
22793}
22794
22796 static const MCPhysReg RCRegs[] = {ARM::FPSCR_RM};
22797 return RCRegs;
22798}
22799
22802 ComplexDeinterleavingRotation Rotation, Value *InputA, Value *InputB,
22803 Value *Accumulator) const {
22804
22806
22807 unsigned TyWidth = Ty->getScalarSizeInBits() * Ty->getNumElements();
22808
22809 assert(TyWidth >= 128 && "Width of vector type must be at least 128 bits");
22810
22811 if (TyWidth > 128) {
22812 int Stride = Ty->getNumElements() / 2;
22813 auto SplitSeq = llvm::seq<int>(0, Ty->getNumElements());
22814 auto SplitSeqVec = llvm::to_vector(SplitSeq);
22815 ArrayRef<int> LowerSplitMask(&SplitSeqVec[0], Stride);
22816 ArrayRef<int> UpperSplitMask(&SplitSeqVec[Stride], Stride);
22817
22818 auto *LowerSplitA = B.CreateShuffleVector(InputA, LowerSplitMask);
22819 auto *LowerSplitB = B.CreateShuffleVector(InputB, LowerSplitMask);
22820 auto *UpperSplitA = B.CreateShuffleVector(InputA, UpperSplitMask);
22821 auto *UpperSplitB = B.CreateShuffleVector(InputB, UpperSplitMask);
22822 Value *LowerSplitAcc = nullptr;
22823 Value *UpperSplitAcc = nullptr;
22824
22825 if (Accumulator) {
22826 LowerSplitAcc = B.CreateShuffleVector(Accumulator, LowerSplitMask);
22827 UpperSplitAcc = B.CreateShuffleVector(Accumulator, UpperSplitMask);
22828 }
22829
22830 auto *LowerSplitInt = createComplexDeinterleavingIR(
22831 B, OperationType, Rotation, LowerSplitA, LowerSplitB, LowerSplitAcc);
22832 auto *UpperSplitInt = createComplexDeinterleavingIR(
22833 B, OperationType, Rotation, UpperSplitA, UpperSplitB, UpperSplitAcc);
22834
22835 ArrayRef<int> JoinMask(&SplitSeqVec[0], Ty->getNumElements());
22836 return B.CreateShuffleVector(LowerSplitInt, UpperSplitInt, JoinMask);
22837 }
22838
22839 auto *IntTy = Type::getInt32Ty(B.getContext());
22840
22841 ConstantInt *ConstRotation = nullptr;
22842 if (OperationType == ComplexDeinterleavingOperation::CMulPartial) {
22843 ConstRotation = ConstantInt::get(IntTy, (int)Rotation);
22844
22845 if (Accumulator)
22846 return B.CreateIntrinsic(Intrinsic::arm_mve_vcmlaq, Ty,
22847 {ConstRotation, Accumulator, InputB, InputA});
22848 return B.CreateIntrinsic(Intrinsic::arm_mve_vcmulq, Ty,
22849 {ConstRotation, InputB, InputA});
22850 }
22851
22852 if (OperationType == ComplexDeinterleavingOperation::CAdd) {
22853 // 1 means the value is not halved.
22854 auto *ConstHalving = ConstantInt::get(IntTy, 1);
22855
22857 ConstRotation = ConstantInt::get(IntTy, 0);
22859 ConstRotation = ConstantInt::get(IntTy, 1);
22860
22861 if (!ConstRotation)
22862 return nullptr; // Invalid rotation for arm_mve_vcaddq
22863
22864 return B.CreateIntrinsic(Intrinsic::arm_mve_vcaddq, Ty,
22865 {ConstHalving, ConstRotation, InputA, InputB});
22866 }
22867
22868 return nullptr;
22869}
static bool isAddSubSExt(SDValue N, SelectionDAG &DAG)
static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt)
isVShiftRImm - Check if this is a valid build_vector for the immediate operand of a vector shift righ...
auto * MemN
static bool isExtendedBUILD_VECTOR(SDValue N, SelectionDAG &DAG, bool isSigned)
static SDValue carryFlagToValue(SDValue Glue, EVT VT, SelectionDAG &DAG, bool Invert)
static SDValue overflowFlagToValue(SDValue Glue, EVT VT, SelectionDAG &DAG)
static bool isZeroExtended(SDValue N, SelectionDAG &DAG)
unsigned NumParts
return SDValue()
static bool isCMN(SDValue Op, ISD::CondCode CC, SelectionDAG &DAG)
static const MCPhysReg GPRArgRegs[]
static SDValue valueToCarryFlag(SDValue Value, SelectionDAG &DAG, bool Invert)
constexpr MVT FlagsVT
Value type used for NZCV flags.
static unsigned getCmpOperandFoldingProfit(SDValue Op, bool AllowExtend)
Returns how profitable it is to fold a comparison's operand's shift and/or extension operations.
static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt)
getVShiftImm - Check if this is a valid build_vector for the immediate operand of a vector shift oper...
static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm, const APInt &Demanded, TargetLowering::TargetLoweringOpt &TLO, unsigned NewOpc)
static bool isSafeSignedCMN(SDValue Op, SelectionDAG &DAG)
static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG)
static bool isSignExtended(SDValue N, SelectionDAG &DAG)
const AArch64Subtarget & Subtarget
const TargetLowering & TLI
SDValue Pred
static bool isAddSubZExt(SDValue N, SelectionDAG &DAG)
static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt)
isVShiftLImm - Check if this is a valid build_vector for the immediate operand of a vector shift left...
static bool canGuaranteeTCO(CallingConv::ID CC, bool GuaranteeTailCalls)
Return true if the calling convention is one that we can guarantee TCO for.
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
amdgpu aa AMDGPU Address space based Alias Analysis Wrapper
uint64_t uint64_t
uint64_t Imm
static bool isConstant(const MachineInstr &MI)
constexpr LLT F64
constexpr LLT S1
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG)
static bool isStore(int Opcode)
static bool isThumb(const MCSubtargetInfo &STI)
static SDValue PerformExtractEltToVMOVRRD(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
static bool isIncompatibleReg(const MCPhysReg &PR, MVT VT)
static SDValue PerformVQDMULHCombine(SDNode *N, SelectionDAG &DAG)
static SDValue PerformVECTOR_DEINTERLEAVECombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG, const ARMSubtarget *ST)
static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *ST)
static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, const ARMSubtarget *ST)
static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, const EVT &OrigTy, const EVT &ExtTy, unsigned ExtOpcode)
AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total value size to 64 bits.
static cl::opt< unsigned > ConstpoolPromotionMaxSize("arm-promote-constant-max-size", cl::Hidden, cl::desc("Maximum size of constant to promote into a constant pool"), cl::init(64))
static bool isZeroOrAllOnes(SDValue N, bool AllOnes)
static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, const ARMSubtarget *ST)
static bool isVTBLMask(ArrayRef< int > M, EVT VT)
static SDValue PerformSUBCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
static cl::opt< bool > EnableConstpoolPromotion("arm-promote-constant", cl::Hidden, cl::desc("Enable / disable promotion of unnamed_addr constants into " "constant pools"), cl::init(false))
static SDValue PerformFAddVSelectCombine(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *Subtarget)
static SDValue PerformExtractFpToIntStores(StoreSDNode *St, SelectionDAG &DAG)
static SDValue PerformVDUPCombine(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *Subtarget)
PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
static SDValue PerformExtractEltCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *ST)
static const APInt * isPowerOf2Constant(SDValue V)
static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *Subtarget)
PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) can replace combinations of ...
static SDValue performSplitConstantStore(StoreSDNode *St, SelectionDAG &DAG, const ARMSubtarget *Subtarget)
static SDValue PerformVMOVhrCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG)
static SDValue LowerVECTOR_SHUFFLEUsingOneOff(SDValue Op, ArrayRef< int > ShuffleMask, SelectionDAG &DAG)
static bool isValidMVECond(unsigned CC, bool IsFloat)
static SDValue PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC)
IntCCToARMCC - Convert a DAG integer condition code to an ARM CC.
static SDValue PerformSTORECombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
PerformSTORECombine - Target-specific dag combine xforms for ISD::STORE.
static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG, const ARMSubtarget *ST)
static bool isGTorGE(ISD::CondCode CC)
static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a vldN-lane (N > 1) intrinsic,...
static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask)
static bool isReverseMask(ArrayRef< int > M, EVT VT)
static SDValue PerformLegalizedVECTOR_DEINTERLEAVECombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG, const ARMSubtarget *Subtarget)
static SDValue PerformSELECTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
static SDValue PerformVECTOR_REG_CASTCombine(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *ST)
static SDValue PerformVMulVCTPCombine(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *Subtarget)
PerformVMulVCTPCombine - VCVT (fixed-point to floating-point, Advanced SIMD) can replace combinations...
static SDValue createGPRPairNode2xi32(SelectionDAG &DAG, SDValue V0, SDValue V1)
static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG)
static bool findPointerConstIncrement(SDNode *N, SDValue *Ptr, SDValue *CInc)
static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG, const ARMSubtarget *ST)
static bool CanInvertMVEVCMP(SDValue N)
static SDValue PerformLongShiftCombine(SDNode *N, SelectionDAG &DAG)
static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
static SDValue PerformShiftCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *ST)
PerformShiftCombine - Checks for immediate versions of vector shifts and lowers them.
static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, ARMCC::CondCodes &CondCode2)
FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG)
static SDValue PerformVMOVrsCombine(SDNode *N, SelectionDAG &DAG)
static EVT getVectorTyFromPredicateVector(EVT VT)
static SDValue PerformFADDVCMLACombine(SDNode *N, SelectionDAG &DAG)
static SDValue handleCMSEValue(const SDValue &Value, const ISD::InputArg &Arg, SelectionDAG &DAG, const SDLoc &DL)
static SDValue PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
static bool isSRL16(const SDValue &Op)
static SDValue PerformVMOVrhCombine(SDNode *N, SelectionDAG &DAG)
static SDValue PerformLOADCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
static SDValue IsCMPZCSINC(SDNode *Cmp, ARMCC::CondCodes &CC)
static unsigned getPointerConstIncrement(unsigned Opcode, SDValue Ptr, SDValue Inc, const SelectionDAG &DAG)
static SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, TargetLowering::DAGCombinerInfo &DCI)
static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget)
static Register genTPEntry(MachineBasicBlock *TpEntry, MachineBasicBlock *TpLoopBody, MachineBasicBlock *TpExit, Register OpSizeReg, const TargetInstrInfo *TII, DebugLoc Dl, MachineRegisterInfo &MRI)
Adds logic in loop entry MBB to calculate loop iteration count and adds t2WhileLoopSetup and t2WhileL...
static SDValue createGPRPairNodei64(SelectionDAG &DAG, SDValue V)
static bool isLTorLE(ISD::CondCode CC)
static SDValue PerformVCMPCombine(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *Subtarget)
static SDValue PerformMVEVMULLCombine(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *Subtarget)
static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, SelectionDAG &DAG)
static SDValue performNegCMovCombine(SDNode *N, SelectionDAG &DAG)
static EVT getExtensionTo64Bits(const EVT &OrigVT)
static TargetLowering::ArgListTy getDivRemArgList(const SDNode *N, FunctionType *FuncTy, const AttributeList &FuncAttrs, RTLIB::LibcallImpl LCImpl)
static SDValue PerformBITCASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *ST)
static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG)
static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr, MachineBasicBlock *BB, const TargetRegisterInfo *TRI)
static SDValue PerformInterleavedStoreCombine(StoreSDNode *ST, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG, const ARMSubtarget *Subtarget)
static SDValue PerformCMPZCombine(SDNode *N, SelectionDAG &DAG)
static bool hasNormalLoadOperand(SDNode *N)
hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node are normal,...
static SDValue PerformInsertEltCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
PerformInsertEltCombine - Target-specific dag combine xforms for ISD::INSERT_VECTOR_ELT.
static SDValue PerformVDUPLANECombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
PerformVDUPLANECombine - Target-specific dag combine xforms for ARMISD::VDUPLANE.
static SDValue LowerBuildVectorOfFPTrunc(SDValue BV, SelectionDAG &DAG, const ARMSubtarget *ST)
static cl::opt< unsigned > ConstpoolPromotionMaxTotal("arm-promote-constant-max-total", cl::Hidden, cl::desc("Maximum size of ALL constants to promote into a constant pool"), cl::init(128))
static SDValue LowerTruncatei1(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *ST)
static RTLIB::Libcall getDivRemLibcall(const SDNode *N, MVT::SimpleValueType SVT)
static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG &DAG)
SkipLoadExtensionForVMULL - return a load of the original vector size that does not do any sign/zero ...
static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
PerformADDCombineWithOperands - Try DAG combinations for an ADD with operands N0 and N1.
static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT, SelectionDAG &DAG)
static SDValue matchCSET(unsigned &Opcode, bool &InvertCond, SDValue TrueVal, SDValue FalseVal, const ARMSubtarget *Subtarget)
static bool isSequentialConcatOfVectorInterleave(SDNode *N, SmallVectorImpl< SDValue > &Ops)
static SDValue PerformORCombineToSMULWBT(SDNode *OR, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG, const ARMSubtarget *ST)
static SDValue FindBFIToCombineWith(SDNode *N)
static SDValue LowerADDSUBSAT(SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget)
static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, bool &swpCmpOps, bool &swpVselOps)
static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG)
static bool isS16(const SDValue &Op, SelectionDAG &DAG)
static bool isSRA16(const SDValue &Op)
static SDValue AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op, ArrayRef< int > ShuffleMask, SelectionDAG &DAG)
static SDValue LowerInterruptReturn(SmallVectorImpl< SDValue > &RetOps, const SDLoc &DL, SelectionDAG &DAG)
static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG, const ARMSubtarget *ST)
static SDValue getInvertedARMCondCode(SDValue ARMcc, SelectionDAG &DAG)
static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, SelectionDAG &DAG)
static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, SDValue &RetVal1, SDValue &RetVal2)
static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG, const ARMSubtarget *ST)
static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *ST)
static SDValue PerformVLDCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
static bool isSHL16(const SDValue &Op)
static bool hasNativeAtomics(const ARMSubtarget &ST)
static bool isVEXTMask(ArrayRef< int > M, EVT VT, bool &ReverseVEXT, unsigned &Imm)
static SDValue PerformMVEVLDCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
cl::opt< unsigned > ArmMaxBaseUpdatesToCheck("arm-max-base-updates-to-check", cl::Hidden, cl::desc("Maximum number of base-updates to check generating postindex."), cl::init(64))
static bool isTruncMask(ArrayRef< int > M, EVT VT, bool Top, bool SingleSource)
static SDValue PerformADDCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2)
Return the load opcode for a given load size.
static SDValue LowerADDSUBO_CARRY(SDValue Op, SelectionDAG &DAG, unsigned Opcode, bool IsSigned)
static bool isLegalT2AddressImmediate(int64_t V, EVT VT, const ARMSubtarget *Subtarget)
static bool isLegalMVEShuffleOp(unsigned PFEntry)
static SDValue PerformSignExtendInregCombine(SDNode *N, SelectionDAG &DAG)
static SDValue PerformShuffleVMOVNCombine(ShuffleVectorSDNode *N, SelectionDAG &DAG)
static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG)
PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for ISD::VECTOR_SHUFFLE.
static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG)
SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, ANY_EXTEND,...
static int getNegationCost(SDValue Op)
static bool isVMOVNTruncMask(ArrayRef< int > M, EVT ToVT, bool rev)
static SDValue PerformVQMOVNCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
static MachineBasicBlock * OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ)
static SDValue LowerVecReduceMinMax(SDValue Op, SelectionDAG &DAG, const ARMSubtarget *ST)
static SDValue PerformFPExtendCombine(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *ST)
static SDValue PerformAddcSubcCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
static SDValue PerformVSELECTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
static SDValue PerformVECREDUCE_ADDCombine(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *ST)
static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl)
getZeroVector - Returns a vector of specified type with all zero elements.
static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St, SelectionDAG &DAG)
static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, bool isSEXTLoad, SDValue &Base, SDValue &Offset, bool &isInc, SelectionDAG &DAG)
static ARMCC::CondCodes getVCMPCondCode(SDValue N)
static cl::opt< bool > ARMInterworking("arm-interworking", cl::Hidden, cl::desc("Enable / disable ARM interworking (for debugging only)"), cl::init(true))
static void ReplaceREADCYCLECOUNTER(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG, const ARMSubtarget *Subtarget)
static SDValue PerformORCombineToBFI(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, SDValue &CC, bool &Invert, SDValue &OtherOp, SelectionDAG &DAG)
static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG, const ARMSubtarget *ST)
static SDValue PerformVSetCCToVCTPCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
static SDValue LowerBUILD_VECTORToVIDUP(SDValue Op, SelectionDAG &DAG, const ARMSubtarget *ST)
static bool isZeroVector(SDValue N)
static SDValue PerformAddeSubeCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
static void ReplaceCMP_SWAP_64Results(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG)
static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, const SDValue TrueVal, const SDValue FalseVal, const ISD::CondCode CC, const SDValue K)
static bool isLegalLogicalImmediate(unsigned Imm, const ARMSubtarget *Subtarget)
static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG)
static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, const TargetInstrInfo *TII, const DebugLoc &dl, unsigned StSize, unsigned Data, unsigned AddrIn, unsigned AddrOut, bool IsThumb1, bool IsThumb2)
Emit a post-increment store operation with given size.
static bool isVMOVNMask(ArrayRef< int > M, EVT VT, bool Top, bool SingleSource)
static SDValue CombineBaseUpdate(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, NEON load/store intrinsics,...
static SDValue LowerSaturatingConditional(SDValue Op, SelectionDAG &DAG)
static SDValue PerformSubCSINCCombine(SDNode *N, SelectionDAG &DAG)
static SDValue PerformVMOVRRDCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
PerformVMOVRRDCombine - Target-specific dag combine xforms for ARMISD::VMOVRRD.
static SDValue LowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget)
static SDValue PerformCSETCombine(SDNode *N, SelectionDAG &DAG)
static SDValue PerformVMOVNCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
static SDValue PerformInsertSubvectorCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
static SDValue LowerVectorExtend(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *Subtarget)
static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain)
static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, ArrayRef< int > ShuffleMask, SelectionDAG &DAG)
static SDValue PerformVMULCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
PerformVMULCombine Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the special multi...
static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG)
static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, SDValue RHS, SelectionDAG &DAG, const SDLoc &dl)
GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit the specified operations t...
static SDValue PerformBFICombine(SDNode *N, SelectionDAG &DAG)
static SDValue PerformORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
PerformORCombine - Target-specific dag combine xforms for ISD::OR.
static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG)
static SDValue PerformTruncatingStoreCombine(StoreSDNode *St, SelectionDAG &DAG)
static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, const TargetInstrInfo *TII, const DebugLoc &dl, unsigned LdSize, unsigned Data, unsigned AddrIn, unsigned AddrOut, bool IsThumb1, bool IsThumb2)
Emit a post-increment load operation with given size.
static SDValue TryDistrubutionADDVecReduce(SDNode *N, SelectionDAG &DAG)
static bool isValidBaseUpdate(SDNode *N, SDNode *User)
static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, const ARMSubtarget *ST, const SDLoc &dl)
static bool IsQRMVEInstruction(const SDNode *N, const SDNode *Op)
static SDValue PerformMinMaxToSatCombine(SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget)
static SDValue PerformXORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, Align Alignment, bool isSEXTLoad, bool IsMasked, bool isLE, SDValue &Base, SDValue &Offset, bool &isInc, SelectionDAG &DAG)
std::pair< unsigned, const TargetRegisterClass * > RCPair
static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, TargetLowering::DAGCombinerInfo &DCI, bool AllOnes=false)
static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *ST)
PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, ISD::ZERO_EXTEND,...
static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG, const ARMSubtarget *ST)
cl::opt< unsigned > MVEMaxSupportedInterleaveFactor("mve-max-interleave-factor", cl::Hidden, cl::desc("Maximum interleave factor for MVE VLDn to generate."), cl::init(2))
static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, unsigned SplatBitSize, SelectionDAG &DAG, const SDLoc &dl, EVT &VT, EVT VectorVT, VMOVModImmType type)
isVMOVModifiedImm - Check if the specified splat value corresponds to a valid vector constant for a N...
static SDValue LowerBuildVectorOfFPExt(SDValue BV, SelectionDAG &DAG, const ARMSubtarget *ST)
static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, SelectionDAG &DAG)
BC is a bitcast that is about to be turned into a VMOVDRR.
static SDValue promoteToConstantPool(const ARMTargetLowering *TLI, const GlobalValue *GV, SelectionDAG &DAG, EVT PtrVT, const SDLoc &dl)
static unsigned isNEONTwoResultShuffleMask(ArrayRef< int > ShuffleMask, EVT VT, unsigned &WhichResult, bool &isV_UNDEF)
Check if ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), and return the corresponding AR...
static bool BitsProperlyConcatenate(const APInt &A, const APInt &B)
static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, bool isSEXTLoad, SDValue &Base, SDValue &Offset, bool &isInc, SelectionDAG &DAG)
static SDValue LowerVecReduce(SDValue Op, SelectionDAG &DAG, const ARMSubtarget *ST)
static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG)
static bool TryCombineBaseUpdate(struct BaseUpdateTarget &Target, struct BaseUpdateUser &User, bool SimpleConstIncOnly, TargetLowering::DAGCombinerInfo &DCI)
static bool allUsersAreInFunction(const Value *V, const Function *F)
Return true if all users of V are within function F, looking through ConstantExprs.
static bool isSingletonVEXTMask(ArrayRef< int > M, EVT VT, unsigned &Imm)
static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG)
PerformVMOVDRRCombine - Target-specific dag combine xforms for ARMISD::VMOVDRR.
static SDValue PerformLegalizedInterleavedStoreCombine(StoreSDNode *ST, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG, const ARMSubtarget *Subtarget)
static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V, SDValue &SatK)
static bool isLegalAddressImmediate(int64_t V, EVT VT, const ARMSubtarget *Subtarget)
isLegalAddressImmediate - Return true if the integer value can be used as the offset of the target ad...
static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG, const ARMSubtarget *ST)
static bool isLegalT1AddressImmediate(int64_t V, EVT VT)
static SDValue CombineANDShift(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG)
static SDValue PerformSHLSimplify(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *ST)
static SDValue PerformADDECombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
PerformADDECombine - Target-specific dag combine transform from ARMISD::ADDC, ARMISD::ADDE,...
static SDValue PerformReduceShuffleCombine(SDNode *N, SelectionDAG &DAG)
static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *Subtarget)
static SDValue LowerTruncate(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *Subtarget)
static SDValue PerformHWLoopCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *ST)
static SDValue PerformORCombineToShiftInsert(SelectionDAG &DAG, SDValue AndOp, SDValue ShiftOp, EVT VT, SDLoc dl)
static SDValue PerformSplittingMVETruncToNarrowingStores(StoreSDNode *St, SelectionDAG &DAG)
static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, uint64_t &Members)
static SDValue PerformMULCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *Subtarget)
static SDValue LowerReverse_VECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG)
static SDValue getShiftedLowMaskZeroTest(SDValue Value, SelectionDAG &DAG, const SDLoc &DL)
static SDValue PerformANDCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
static SDValue PerformADDVecReduce(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *Subtarget)
static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG)
static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm, bool &Negate)
static bool canChangeToInt(SDValue Op, bool &SeenZero, const ARMSubtarget *Subtarget)
canChangeToInt - Given the fp compare operand, return true if it is suitable to morph to an integer c...
static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2)
Return the store opcode for a given store size.
static bool IsVUZPShuffleNode(SDNode *N)
static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *ST)
static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, MachineInstr &MI, const SDNode *Node)
Attaches vregs to MEMCPY that it will use as scratch registers when it is expanded into LDM/STM.
static bool isFloatingPointZero(SDValue Op)
isFloatingPointZero - Return true if this is +0.0.
static SDValue findMUL_LOHI(SDValue V)
static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG, const ARMSubtarget *ST)
static SDValue PerformORCombine_i1(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *Subtarget)
static SDValue PerformSplittingMVEEXTToWideningLoad(SDNode *N, SelectionDAG &DAG)
static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG)
static void genTPLoopBody(MachineBasicBlock *TpLoopBody, MachineBasicBlock *TpEntry, MachineBasicBlock *TpExit, const TargetInstrInfo *TII, DebugLoc Dl, MachineRegisterInfo &MRI, Register OpSrcReg, Register OpDestReg, Register ElementCountReg, Register TotalIterationsReg, bool IsMemcpy)
Adds logic in the loopBody MBB to generate MVE_VCTP, t2DoLoopDec and t2DoLoopEnd.
static SDValue PerformBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const ARMSubtarget *Subtarget)
PerformBUILD_VECTORCombine - Target-specific dag combine xforms for ISD::BUILD_VECTOR.
static SDValue LowerVecReduceF(SDValue Op, SelectionDAG &DAG, const ARMSubtarget *ST)
static SDValue PerformMinMaxCombine(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *ST)
PerformMinMaxCombine - Target-specific DAG combining for creating truncating saturates.
arm ldst static false bool definesCPSR(const MachineInstr &MI)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
This file a TargetTransformInfoImplBase conforming object specific to the ARM target machine.
Function Alias Analysis false
Function Alias Analysis Results
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
This file implements the BitVector class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static std::optional< bool > isBigEndian(const SmallDenseMap< int64_t, int64_t, 8 > &MemOffset2Idx, int64_t LowestIdx)
Given a map from byte offsets in memory to indices in a load/store, determine if that map corresponds...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static void createLoadIntrinsic(IntrinsicInst *II, LoadInst *LI, dxil::ResourceTypeInfo &RTI)
static void createStoreIntrinsic(IntrinsicInst *II, StoreInst *SI, dxil::ResourceTypeInfo &RTI)
This file defines the DenseMap class.
static bool isSigned(unsigned Opcode)
#define Check(C,...)
#define op(i)
#define im(i)
const HexagonInstrInfo * TII
hexagon merge activate weight
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
std::pair< Value *, Value * > ShuffleOps
We are building a shuffle to create V, which is a sequence of insertelement, extractelement pairs.
static Value * LowerCTPOP(LLVMContext &Context, Value *V, Instruction *IP)
Emit the code to lower ctpop of V before the specified instruction IP.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
static LVOptions Options
Definition LVOptions.cpp:25
lazy value info
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define T
nvptx lower args
uint64_t High
uint64_t IntrinsicInst * II
R600 Clause Merge
SmallVector< MachineOperand, 4 > Cond
int64_t C1
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
int64_t C0
MachineInstr *& Lo
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
Contains matchers for matching SelectionDAG nodes and values.
SI Lower i1 Copies
Func MI getDebugLoc()))
This file contains some templates that are useful if you are working with the STL at all.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
This file contains some functions that are useful when dealing with strings.
This file implements the StringSwitch template, which mimics a switch() statement whose cases are str...
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This file describes how to lower LLVM code to machine code.
static X86::CondCode getSwappedCondition(X86::CondCode CC)
Assuming the flags are set by MI(a,b), return the condition code if we modify the instructions such t...
static constexpr int Concat[]
Value * RHS
Value * LHS
BinaryOperator * Mul
static bool isIntrinsic(const CallBase &Call, Intrinsic::ID ID)
The Input class is used to parse a yaml document into in-memory structs and vectors.
static constexpr roundingMode rmTowardZero
Definition APFloat.h:384
LLVM_ABI bool getExactInverse(APFloat *Inv) const
If this value is normal and has an exact, normal, multiplicative inverse, store it in inv and return ...
Definition APFloat.cpp:6043
APInt bitcastToAPInt() const
Definition APFloat.h:1504
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1465
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1690
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition APInt.cpp:648
unsigned logBase2() const
Definition APInt.h:1781
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:471
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:385
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition APInt.h:860
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
unsigned countr_one() const
Count the number of trailing one bits.
Definition APInt.h:1676
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
const ARMBaseRegisterInfo & getRegisterInfo() const
const uint32_t * getSjLjDispatchPreservedMask(const MachineFunction &MF) const
const MCPhysReg * getCalleeSavedRegs(const MachineFunction *MF) const override
Code Generation virtual methods...
Register getFrameRegister(const MachineFunction &MF) const override
const uint32_t * getCallPreservedMask(const MachineFunction &MF, CallingConv::ID) const override
const uint32_t * getTLSCallPreservedMask(const MachineFunction &MF) const
const uint32_t * getThisReturnPreservedMask(const MachineFunction &MF, CallingConv::ID) const
getThisReturnPreservedMask - Returns a call preserved mask specific to the case that 'returned' is on...
static ARMConstantPoolConstant * Create(const Constant *C, unsigned ID)
static ARMConstantPoolMBB * Create(LLVMContext &C, const MachineBasicBlock *mbb, unsigned ID, unsigned char PCAdj)
static ARMConstantPoolSymbol * Create(LLVMContext &C, StringRef s, unsigned ID, unsigned char PCAdj, ARMCP::ARMCPModifier Modifier=ARMCP::no_modifier, bool AddCurrentAddress=false)
ARMConstantPoolValue - ARM specific constantpool value.
ARMFunctionInfo - This class is derived from MachineFunctionInfo and contains private ARM-specific in...
SmallVectorImpl< ForwardedRegister > & getForwardedMustTailRegParms()
SmallPtrSet< const GlobalVariable *, 2 > & getGlobalsPromotedToConstantPool()
void setArgumentStackToRestore(unsigned v)
void setArgRegsSaveSize(unsigned s)
void setReturnRegsCount(unsigned s)
unsigned getArgRegsSaveSize() const
void markGlobalAsPromotedToConstantPool(const GlobalVariable *GV)
Indicate to the backend that GV has had its storage changed to inside a constant pool.
void setArgumentStackSize(unsigned size)
unsigned getArgumentStackSize() const
bool shouldFoldSelectWithIdentityConstant(unsigned BinOpcode, EVT VT, unsigned SelectOpcode, SDValue X, SDValue Y) const override
Return true if pulling a binary operation into a select with an identity constant is profitable.
bool isReadOnly(const GlobalValue *GV) const
unsigned getMaxSupportedInterleaveFactor() const override
Get the maximum supported factor for interleaved memory accesses.
TargetLoweringBase::AtomicExpansionKind shouldExpandAtomicLoadInIR(LoadInst *LI) const override
Returns how the given (atomic) load should be expanded by the IR-level AtomicExpand pass.
unsigned getNumInterleavedAccesses(VectorType *VecTy, const DataLayout &DL) const
Returns the number of interleaved accesses that will be generated when lowering accesses of the given...
bool shouldInsertFencesForAtomic(const Instruction *I) const override
Whether AtomicExpandPass should automatically insert fences and reduce ordering for this atomic.
Align getABIAlignmentForCallingConv(Type *ArgTy, const DataLayout &DL) const override
Return the correct alignment for the current calling convention.
bool isDesirableToCommuteWithShift(const SDNode *N, CombineLevel Level) const override
Return true if it is profitable to move this shift by a constant amount through its operand,...
ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const override
Examine constraint string and operand type and determine a weight value.
bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I=nullptr) const override
isLegalAddressingMode - Return true if the addressing mode represented by AM is legal for this target...
bool isLegalT2ScaledAddressingMode(const AddrMode &AM, EVT VT) const
bool isLegalT1ScaledAddressingMode(const AddrMode &AM, EVT VT) const
Returns true if the addressing mode representing by AM is legal for the Thumb1 target,...
bool getPreIndexedAddressParts(SDNode *N, SDValue &Base, SDValue &Offset, ISD::MemIndexedMode &AM, SelectionDAG &DAG) const override
getPreIndexedAddressParts - returns true by value, base pointer and offset pointer and addressing mod...
MachineInstr * EmitKCFICheck(MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator &MBBI, const TargetInstrInfo *TII) const override
bool shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, Align &PrefAlign) const override
Return true if the pointer arguments to CI should be aligned by aligning the object whose address is ...
void getTgtMemIntrinsic(SmallVectorImpl< IntrinsicInfo > &Infos, const CallBase &I, MachineFunction &MF, unsigned Intrinsic) const override
getTgtMemIntrinsic - Represent NEON load and store intrinsics as MemIntrinsicNodes.
void ReplaceNodeResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const override
ReplaceNodeResults - Replace the results of node with an illegal result type with new values built ou...
void emitAtomicCmpXchgNoStoreLLBalance(IRBuilderBase &Builder) const override
bool isMulAddWithConstProfitable(SDValue AddNode, SDValue ConstNode) const override
Return true if it may be profitable to transform (mul (add x, c1), c2) -> (add (mul x,...
bool isLegalAddImmediate(int64_t Imm) const override
isLegalAddImmediate - Return true if the specified immediate is legal add immediate,...
EVT getOptimalMemOpType(LLVMContext &Context, const MemOp &Op, const AttributeList &FuncAttributes) const override
Returns the target specific optimal type for load and store operations as a result of memset,...
Instruction * emitTrailingFence(IRBuilderBase &Builder, Instruction *Inst, AtomicOrdering Ord) const override
bool isFNegFree(EVT VT) const override
Return true if an fneg operation is free to the point where it is never worthwhile to replace it with...
void finalizeLowering(MachineFunction &MF) const override
Execute target specific actions to finalize target lowering.
SDValue PerformMVETruncCombine(SDNode *N, DAGCombinerInfo &DCI) const
ConstraintType getConstraintType(StringRef Constraint) const override
getConstraintType - Given a constraint letter, return the type of constraint it is for this target.
bool preferIncOfAddToSubOfNot(EVT VT) const override
These two forms are equivalent: sub y, (xor x, -1) add (add x, 1), y The variant with two add's is IR...
FPImmAction getFPImmAction(const APFloat &Imm, EVT VT, bool ForCodeSize=false) const override
Returns how to materialize the specified FP immediate.
void computeKnownBitsForTargetNode(const SDValue Op, KnownBits &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const override
Determine which of the bits specified in Mask are known to be either zero or one and return them in t...
TargetLoweringBase::AtomicExpansionKind shouldExpandAtomicStoreInIR(StoreInst *SI) const override
Returns how the given (atomic) store should be expanded by the IR-level AtomicExpand pass into.
SDValue PerformIntrinsicCombine(SDNode *N, DAGCombinerInfo &DCI) const
PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
bool shouldFoldConstantShiftPairToMask(const SDNode *N) const override
Return true if it is profitable to fold a pair of shifts into a mask.
bool isDesirableToCommuteXorWithShift(const SDNode *N) const override
Return true if it is profitable to combine an XOR of a logical shift to create a logical shift of NOT...
SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const
PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
TargetLoweringBase::AtomicExpansionKind shouldExpandAtomicRMWInIR(const AtomicRMWInst *AI) const override
Returns how the IR-level AtomicExpand pass should expand the given AtomicRMW, if at all.
Value * createComplexDeinterleavingIR(IRBuilderBase &B, ComplexDeinterleavingOperation OperationType, ComplexDeinterleavingRotation Rotation, Value *InputA, Value *InputB, Value *Accumulator=nullptr) const override
Create the IR node for the given complex deinterleaving operation.
bool isComplexDeinterleavingSupported() const override
Does this target support complex deinterleaving.
SDValue PerformMVEExtCombine(SDNode *N, DAGCombinerInfo &DCI) const
FastISel * createFastISel(FunctionLoweringInfo &funcInfo, const TargetLibraryInfo *libInfo, const LibcallLoweringInfo *libcallLowering) const override
createFastISel - This method returns a target specific FastISel object, or null if the target does no...
void insertSSPDeclarations(Module &M, const LibcallLoweringInfo &Libcalls) const override
Inserts necessary declarations for SSP (stack protection) purpose.
bool SimplifyDemandedBitsForTargetNode(SDValue Op, const APInt &OriginalDemandedBits, const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const override
Attempt to simplify any target nodes based on the demanded bits/elts, returning true on success.
EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const override
getSetCCResultType - Return the value type to use for ISD::SETCC.
MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const override
This method should be implemented by targets that mark instructions with the 'usesCustomInserter' fla...
Value * emitStoreConditional(IRBuilderBase &Builder, Value *Val, Value *Addr, AtomicOrdering Ord) const override
Perform a store-conditional operation to Addr.
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override
This callback is invoked for operations that are unsupported by the target, which are registered to u...
CCAssignFn * CCAssignFnForReturn(CallingConv::ID CC, bool isVarArg) const
void AdjustInstrPostInstrSelection(MachineInstr &MI, SDNode *Node) const override
This method should be implemented by targets that mark instructions with the 'hasPostISelHook' flag.
bool isTruncateFree(Type *SrcTy, Type *DstTy) const override
Return true if it's free to truncate a value of type FromTy to type ToTy.
bool isShuffleMaskLegal(ArrayRef< int > M, EVT VT) const override
isShuffleMaskLegal - Targets can use this to indicate that they only support some VECTOR_SHUFFLE oper...
Register getExceptionPointerRegister(ExceptionHandling EH, const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception address on entry to an ...
TargetLoweringBase::AtomicExpansionKind shouldExpandAtomicCmpXchgInIR(const AtomicCmpXchgInst *AI) const override
Returns how the given atomic cmpxchg should be expanded by the IR-level AtomicExpand pass.
bool shouldConvertConstantLoadToIntImm(const APInt &Imm, Type *Ty) const override
Returns true if it is beneficial to convert a load of a constant to just the constant itself.
bool lowerInterleavedStore(Instruction *Store, Value *Mask, ShuffleVectorInst *SVI, unsigned Factor, const APInt &GapMask) const override
Lower an interleaved store into a vstN intrinsic.
const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const override
getRegClassFor - Return the register class that should be used for the specified value type.
bool useLoadStackGuardNode(const Module &M) const override
If this function returns true, SelectionDAGBuilder emits a LOAD_STACK_GUARD node when it is lowering ...
bool lowerInterleavedLoad(Instruction *Load, Value *Mask, ArrayRef< ShuffleVectorInst * > Shuffles, ArrayRef< unsigned > Indices, unsigned Factor, const APInt &GapMask) const override
Lower an interleaved load into a vldN intrinsic.
std::pair< const TargetRegisterClass *, uint8_t > findRepresentativeClass(const TargetRegisterInfo *TRI, MVT VT) const override
Return the largest legal super-reg register class of the register class for the specified type and it...
bool preferSelectsOverBooleanArithmetic(EVT VT) const override
Should we prefer selects to doing arithmetic on boolean types.
bool isZExtFree(SDValue Val, EVT VT2) const override
Return true if zero-extending the specific node Val to type VT2 is free (either because it's implicit...
bool isCheapToSpeculateCttz(Type *Ty) const override
Return true if it is cheap to speculate a call to intrinsic cttz.
SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override
This method will be invoked for all target nodes and for any target-independent nodes that the target...
bool isCheapToSpeculateCtlz(Type *Ty) const override
Return true if it is cheap to speculate a call to intrinsic ctlz.
bool targetShrinkDemandedConstant(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, TargetLoweringOpt &TLO) const override
bool hasAndNot(SDValue Y) const override
Return true if the target has a bitwise and-not operation: X = ~A & B This can be used to simplify se...
Register getExceptionSelectorRegister(ExceptionHandling EH, const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception typeid on entry to a la...
ExtractSubvectorCost getExtractSubvectorCost(EVT ResVT, EVT SrcVT, unsigned Index) const override
Return the cost of EXTRACT_SUBVECTOR for this result type with this index.
CallingConv::ID getEffectiveCallingConv(CallingConv::ID CC, bool isVarArg) const
getEffectiveCallingConv - Get the effective calling convention, taking into account presence of float...
ARMTargetLowering(const TargetMachine &TM, const ARMSubtarget &STI)
bool isComplexDeinterleavingOperationSupported(ComplexDeinterleavingOperation Operation, Type *Ty) const override
Does this target support complex deinterleaving with the given operation and type.
bool supportKCFIBundles() const override
Return true if the target supports kcfi operand bundles.
SDValue PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const
PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
Value * getIRStackGuard(IRBuilderBase &IRB, const LibcallLoweringInfo &Libcalls) const override
If the target has a standard location for the stack protector guard, returns the address of that loca...
Type * shouldConvertSplatType(ShuffleVectorInst *SVI) const override
Given a shuffle vector SVI representing a vector splat, return a new scalar type of size equal to SVI...
Value * emitLoadLinked(IRBuilderBase &Builder, Type *ValueTy, Value *Addr, AtomicOrdering Ord) const override
Perform a load-linked operation on Addr, returning a "Value *" with the corresponding pointee type.
Instruction * makeDMB(IRBuilderBase &Builder, ARM_MB::MemBOpt Domain) const
bool isLegalICmpImmediate(int64_t Imm) const override
isLegalICmpImmediate - Return true if the specified immediate is legal icmp immediate,...
const char * LowerXConstraint(EVT ConstraintVT) const override
Try to replace an X constraint, which matches anything, with another that has more specific requireme...
unsigned getJumpTableEncoding() const override
Return the entry encoding for a jump table in the current function.
bool isDesirableToTransformToIntegerOp(unsigned Opc, EVT VT) const override
Return true if it is profitable for dag combiner to transform a floating point op of specified opcode...
CCAssignFn * CCAssignFnForCall(CallingConv::ID CC, bool isVarArg) const
bool allowsMisalignedMemoryAccesses(EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, unsigned *Fast) const override
allowsMisalignedMemoryAccesses - Returns true if the target allows unaligned memory accesses of the s...
bool isLegalInterleavedAccessType(unsigned Factor, FixedVectorType *VecTy, Align Alignment, const DataLayout &DL) const
Returns true if VecTy is a legal interleaved access type.
bool isVectorLoadExtDesirable(SDValue ExtVal) const override
Return true if folding a vector load into ExtVal (a sign, zero, or any extend node) is profitable.
bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx, unsigned &Cost) const override
Return true if the target can combine store(extractelement VectorTy,Idx).
bool useSoftFloat() const override
bool alignLoopsWithOptSize() const override
Should loops be aligned even when the function is marked OptSize (but not MinSize).
SDValue PerformCMOVToBFICombine(SDNode *N, SelectionDAG &DAG) const
bool allowTruncateForTailCall(Type *Ty1, Type *Ty2) const override
Return true if a truncation from FromTy to ToTy is permitted when deciding whether a call is in tail ...
void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const override
LowerAsmOperandForConstraint - Lower the specified operand into the Ops vector.
bool hasAndNotCompare(SDValue V) const override
Return true if the target should transform: (X & Y) == Y ---> (~X & Y) == 0 (X & Y) !...
std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const override
Given a physical register constraint (e.g.
bool shouldConvertFpToSat(unsigned Op, EVT FPVT, EVT VT) const override
Should we generate fp_to_si_sat and fp_to_ui_sat from type FPVT to type VT.
bool functionArgumentNeedsConsecutiveRegisters(Type *Ty, CallingConv::ID CallConv, bool isVarArg, const DataLayout &DL) const override
Returns true if an argument of type Ty needs to be passed in a contiguous block of registers in calli...
bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const override
Return true if folding a constant offset with the given GlobalAddress is legal.
const ARMBaseTargetMachine & getTM() const
bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const override
Return if the target supports combining a chain like:
ShiftLegalizationStrategy preferredShiftLegalizationStrategy(SelectionDAG &DAG, SDNode *N, unsigned ExpansionFactor) const override
bool getPostIndexedAddressParts(SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset, ISD::MemIndexedMode &AM, SelectionDAG &DAG) const override
getPostIndexedAddressParts - returns true by value, base pointer and offset pointer and addressing mo...
Instruction * emitLeadingFence(IRBuilderBase &Builder, Instruction *Inst, AtomicOrdering Ord) const override
Inserts in the IR a target-specific intrinsic specifying a fence.
bool canCreateUndefOrPoisonForTargetNode(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, UndefPoisonKind Kind, bool ConsiderFlags, unsigned Depth) const override
Return true if Op can create undef or poison from non-undef & non-poison operands.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
An instruction that atomically checks whether a specified value is in a memory location,...
an instruction that atomically reads a memory location, combines it with another value,...
bool isFloatingPointOperation() const
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
static LLVM_ABI BaseIndexOffset match(const SDNode *N, const SelectionDAG &DAG)
Parses tree in N for base, index, and fixed/scalable offsets.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
The address of a basic block.
Definition Constants.h:1088
static constexpr BranchProbability getZero()
A "pseudo-class" with methods for operating on BUILD_VECTORs.
LLVM_ABI bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef, unsigned &SplatBitSize, bool &HasAnyUndefs, unsigned MinSplatBits=0, bool isBigEndian=false) const
Check if this is a constant splat, and if so, find the smallest element size that splats the vector.
LLVM_ABI int32_t getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, uint32_t BitWidth) const
If this is a constant FP splat and the splatted constant FP is an exact power or 2,...
CCState - This class holds information needed while lowering arguments and return values.
void getInRegsParamInfo(unsigned InRegsParamRecordIndex, unsigned &BeginReg, unsigned &EndReg) const
unsigned getFirstUnallocated(ArrayRef< MCPhysReg > Regs) const
getFirstUnallocated - Return the index of the first unallocated register in the set,...
LLVM_ABI void analyzeMustTailForwardedRegisters(SmallVectorImpl< ForwardedRegister > &Forwards, ArrayRef< MVT > RegParmTypes, CCAssignFn Fn)
Compute the set of registers that need to be preserved and forwarded to any musttail calls.
static LLVM_ABI bool resultsCompatible(CallingConv::ID CalleeCC, CallingConv::ID CallerCC, MachineFunction &MF, LLVMContext &C, const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn CalleeFn, CCAssignFn CallerFn)
Returns true if the results of the two calling conventions are compatible.
MCRegister AllocateReg(MCPhysReg Reg)
AllocateReg - Attempt to allocate one register.
LLVM_ABI bool CheckReturn(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
CheckReturn - Analyze the return values of a function, returning true if the return can be performed ...
LLVM_ABI void AnalyzeReturn(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
AnalyzeReturn - Analyze the returned values of a return, incorporating info about the result values i...
unsigned getInRegsParamsProcessed() const
uint64_t getStackSize() const
Returns the size of the currently allocated portion of the stack.
void addInRegsParamInfo(unsigned RegBegin, unsigned RegEnd)
LLVM_ABI void AnalyzeFormalArguments(const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn Fn)
AnalyzeFormalArguments - Analyze an array of argument values, incorporating info about the formals in...
unsigned getInRegsParamsCount() const
CCValAssign - Represent assignment of one arg/retval to a location.
Register getLocReg() const
LocInfo getLocInfo() const
bool needsCustom() const
int64_t getLocMemOffset() const
unsigned getValNo() const
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
AttributeList getAttributes() const
Return the attributes for this call.
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
This class represents a function call, abstracting a target machine's calling convention.
bool isTailCall() const
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition Constants.h:878
const APFloat & getValueAPF() const
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
MachineConstantPoolValue * getMachineCPVal() const
const Constant * getConstVal() const
LLVM_ABI Type * getType() const
uint64_t getZExtValue() const
const APInt & getAPIntValue() const
int64_t getSExtValue() const
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:220
bool isBigEndian() const
Definition DataLayout.h:221
MaybeAlign getStackAlignment() const
Returns the natural stack alignment, or MaybeAlign() if one wasn't specified.
Definition DataLayout.h:253
LLVM_ABI TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
StringRef getInternalSymbolPrefix() const
Definition DataLayout.h:311
LLVM_ABI Align getPreferredAlign(const GlobalVariable *GV) const
Returns the preferred alignment of the specified global.
LLVM_ABI Align getPrefTypeAlign(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
A debug info location.
Definition DebugLoc.h:127
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
unsigned size() const
Definition DenseMap.h:717
iterator begin()
Definition DenseMap.h:682
This is a fast-path instruction selection class that generates poor code and doesn't support illegal ...
Definition FastISel.h:67
Class to represent fixed width SIMD vectors.
unsigned getNumElements() const
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
Type * getParamType(unsigned i) const
Parameter type accessors.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:705
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
arg_iterator arg_begin()
Definition Function.h:862
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
bool hasStructRetAttr() const
Determine if the function returns a structure through first or second pointer argument.
Definition Function.h:673
const Argument * const_arg_iterator
Definition Function.h:74
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Definition Function.h:230
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
const GlobalValue * getGlobal() const
bool isDSOLocal() const
bool hasExternalWeakLinkage() const
bool hasDLLImportStorageClass() const
Module * getParent()
Get the module that this global value is contained inside of...
bool isStrongDefinitionForLinker() const
Returns true if this global's definition will be the one chosen by the linker.
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
Value * CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0, const Twine &Name="")
Definition IRBuilder.h:2026
Module * getModule() const
Get the module.
Definition IRBuilder.h:190
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2640
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition IRBuilder.h:571
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition IRBuilder.h:518
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
LLVM_ABI bool hasAtomicStore() const LLVM_READONLY
Return true if this atomic instruction stores to memory.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
bool isIndexed() const
Return true if this is a pre/post inc/dec load/store.
Tracks which library functions to use for a particular subtarget or function.
const RTLIB::RuntimeLibcallsInfo & getRuntimeLibcallsInfo() const
CallingConv::ID getLibcallImplCallingConv(RTLIB::LibcallImpl Call) const
Get the CallingConv that should be used for the specified libcall.
RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Return the lowering's selection of implementation call for Call.
An instruction for reading from memory.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
This class is used to represent ISD::LOAD nodes.
const SDValue & getBasePtr() const
Describe properties that are true of each instruction in the target description file.
Machine Value Type.
static MVT getFloatingPointVT(unsigned BitWidth)
static auto integer_fixedlen_vector_valuetypes()
SimpleValueType SimpleTy
uint64_t getScalarSizeInBits() const
unsigned getVectorNumElements() const
bool isInteger() const
Return true if this is an integer or a vector integer type.
static LLVM_ABI MVT getVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
static auto integer_valuetypes()
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
static auto fixedlen_vector_valuetypes()
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
bool isScalarInteger() const
Return true if this is an integer, not including vectors.
static MVT getVectorVT(MVT VT, unsigned NumElements)
MVT getVectorElementType() const
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
static MVT getIntegerVT(unsigned BitWidth)
static auto fp_valuetypes()
bool is64BitVector() const
Return true if this is a 64-bit vector type.
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
bool isEHPad() const
Returns true if the block is a landing pad.
LLVM_ABI MachineBasicBlock * getFallThrough(bool JumpToFallThrough=true)
Return the fallthrough block if the block can implicitly transfer control to the block after it by fa...
void setCallFrameSize(unsigned N)
Set the call frame size on entry to this basic block.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI bool canFallThrough()
Return true if the block can implicitly transfer control to the block after it by falling off the end...
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
Instructions::iterator instr_iterator
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
LLVM_ABI MachineBasicBlock * splitAt(MachineInstr &SplitInst, bool UpdateLiveIns=true, LiveIntervals *LIS=nullptr)
Split a basic block into 2 pieces at SplitPoint.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
iterator_range< succ_iterator > successors()
iterator_range< pred_iterator > predecessors()
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI void moveAfter(MachineBasicBlock *NewBefore)
LLVM_ABI bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
void setIsEHPad(bool V=true)
Indicates the block is a landing pad.
The MachineConstantPool class keeps track of constants referenced by a function which must be spilled...
LLVM_ABI unsigned getConstantPoolIndex(const Constant *C, Align Alignment)
getConstantPoolIndex - Create a new entry in the constant pool or return an existing one.
LLVM_ABI int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
LLVM_ABI void computeMaxCallFrameSize(MachineFunction &MF, std::vector< MachineBasicBlock::iterator > *FrameSDOps=nullptr)
Computes the maximum size of a callframe.
void setFrameAddressIsTaken(bool T)
void setHasTailCall(bool V=true)
bool hasMustTailInVarArgFunc() const
Returns true if the function is variadic and contains a musttail call.
void setReturnAddressIsTaken(bool s)
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
bool hasVAStart() const
Returns true if the function calls the llvm.va_start intrinsic.
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
int getFunctionContextIndex() const
Return the index for the function context object.
Properties which a MachineFunction may have at a given point in time.
unsigned getFunctionNumber() const
getFunctionNumber - Return a unique ID for the current function.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
void push_back(MachineBasicBlock *MBB)
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
MachineConstantPool * getConstantPool()
getConstantPool - Return the constant pool object for the current function.
const MachineFunctionProperties & getProperties() const
Get the function properties.
Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC)
addLiveIn - Add the specified physical register as a live-in value and create a corresponding virtual...
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & addExternalSymbol(const char *FnName, unsigned TargetFlags=0) const
const MachineInstrBuilder & setOperandDead(unsigned OpIdx) const
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addFrameIndex(int Idx) const
const MachineInstrBuilder & addConstantPoolIndex(unsigned Idx, int Offset=0, unsigned TargetFlags=0) const
const MachineInstrBuilder & addRegMask(const uint32_t *Mask) const
const MachineInstrBuilder & addJumpTableIndex(unsigned Idx, unsigned TargetFlags=0) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
const MachineInstrBuilder & cloneMemRefs(const MachineInstr &OtherMI) const
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
Representation of each machine instruction.
bool readsRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr reads the specified register.
bool definesRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr fully defines the specified register.
MachineOperand * mop_iterator
iterator/begin/end - Iterate over all operands of a machine instruction.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI unsigned createJumpTableIndex(const std::vector< MachineBasicBlock * > &DestBBs)
createJumpTableIndex - Create a new jump table.
@ EK_Inline
EK_Inline - Jump table entries are emitted inline at their point of use.
@ EK_BlockAddress
EK_BlockAddress - Each entry is a plain address of block, e.g.: .word LBB123.
A description of a memory reference used in the backend.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MONonTemporal
The memory access is non-temporal.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
MachineOperand class - Representation of each machine instruction operand.
LLVM_ABI void setIsRenamable(bool Val=true)
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void setIsDead(bool Val=true)
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
static MachineOperand CreateImm(int64_t Val)
Register getReg() const
getReg - Returns the register number.
LLVM_ABI void setIsDef(bool Val=true)
Change a def to a use, or a use to a def.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
This class is used to represent an MLOAD node.
This class is used to represent an MSTORE node.
This SDNode is used for target intrinsics that touch memory and need an associated MachineMemOperand.
This is an abstract virtual class for memory operations.
Align getAlign() const
bool isSimple() const
Returns true if the memory operation is neither atomic or volatile.
MachineMemOperand * getMemOperand() const
Return the unique MachineMemOperand object describing the memory reference performed by operation.
const SDValue & getChain() const
EVT getMemoryVT() const
Return the type of the in-memory value.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition Module.h:328
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
const DebugLoc & getDebugLoc() const
Represents one node in the SelectionDAG.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool hasOneUse() const
Return true if there is exactly one use of this node.
LLVM_ABI bool isOnlyUserOf(const SDNode *N) const
Return true if this node is the only use of N.
ISD::CondCode getOperandCondCode(unsigned Num) const
Helper method returns the CondCode of a CondCodeSDNode.
iterator_range< use_iterator > uses()
SDNodeFlags getFlags() const
static bool hasPredecessorHelper(const SDNode *N, SmallPtrSetImpl< const SDNode * > &Visited, SmallVectorImpl< const SDNode * > &Worklist, unsigned int MaxSteps=0, bool TopologicalPrune=false)
Returns true if N is a predecessor of any node in Worklist.
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
bool use_empty() const
Return true if there are no uses of this node.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
unsigned getNumOperands() const
Return the number of values used by this operation.
const SDValue & getOperand(unsigned Num) const
uint64_t getConstantOperandVal(unsigned Num) const
Helper method returns the integer value of a ConstantSDNode operand.
const APInt & getConstantOperandAPInt(unsigned Num) const
Helper method returns the APInt of a ConstantSDNode operand.
bool isPredecessorOf(const SDNode *N) const
Return true if this node is a predecessor of N.
LLVM_ABI bool hasAnyUseOfValue(unsigned Value) const
Return true if there are any use of the indicated value.
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
void setCFIType(uint32_t Type)
bool isUndef() const
Returns true if the node type is UNDEF or POISON.
iterator_range< user_iterator > users()
void setFlags(SDNodeFlags NewFlags)
user_iterator user_begin() const
Provide iteration support to walk over all users of an SDNode.
op_iterator op_end() const
op_iterator op_begin() const
Represents a use of a SDNode.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
const SDValue & getOperand(unsigned i) const
ISD::CondCode getOperandCondCode(unsigned i) const
const APInt & getConstantOperandAPInt(unsigned i) const
uint64_t getScalarValueSizeInBits() const
unsigned getResNo() const
get the index which selects a specific result in the SDNode
uint64_t getConstantOperandVal(unsigned i) const
unsigned getOpcode() const
unsigned getNumOperands() const
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
LLVM_ABI SDValue getStackArgumentTokenFactor(SDValue Chain)
Compute a TokenFactor to force all the incoming stack arguments to be loaded from the stack.
const TargetSubtargetInfo & getSubtarget() const
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg, SDValue N)
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getSplatValue(SDValue V, bool LegalTypes=false)
If V is a splat vector, return its scalar source operand by extracting that element from the source v...
LLVM_ABI SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget=false, bool IsOpaque=false)
LLVM_ABI MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
LLVM_ABI SDNode * getNodeIfExists(unsigned Opcode, SDVTList VTList, ArrayRef< SDValue > Ops, const SDNodeFlags Flags, bool AllowCommute=false)
Get the specified node if it's already available, or else return NULL.
LLVM_ABI SDValue makeEquivalentMemoryOrdering(SDValue OldChain, SDValue NewMemOpChain)
If an existing load has uses of its chain, create a token factor node with that chain and the new mem...
LLVM_ABI bool areNonVolatileConsecutiveLoads(LoadSDNode *LD, LoadSDNode *Base, TypeSize Bytes, int Dist) const
Return true if loads are next to each other and can be merged.
LLVM_ABI SDValue UnrollVectorOp(SDNode *N, unsigned ResNE=0)
Utility function used by legalize and lowering to "unroll" a vector operation by splitting out the sc...
LLVM_ABI bool haveNoCommonBitsSet(SDValue A, SDValue B) const
Return true if A and B have no common bits set.
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
LLVM_ABI SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef< SDValue > Ops, EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MOLoad|MachineMemOperand::MOStore, LocationSize Size=LocationSize::precise(0), const AAMDNodes &AAInfo=AAMDNodes())
Creates a MemIntrinsicNode that may produce a result and takes a list of operands.
void addNoMergeSiteInfo(const SDNode *Node, bool NoMerge)
Set NoMergeSiteInfo to be associated with Node if NoMerge is true.
std::pair< SDValue, SDValue > SplitVectorOperand(const SDNode *N, unsigned OpNo)
Split the node's operand with EXTRACT_SUBVECTOR and return the low/high part.
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
const TargetLowering & getTargetLoweringInfo() const
SDValue getTargetJumpTable(int JTI, EVT VT, unsigned TargetFlags=0)
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2, SDValue InGlue, const SDLoc &DL)
Return a new CALLSEQ_END node, which always must have a glue result (to ensure it's not CSE'd).
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
LLVM_ABI SDValue getNegative(SDValue Val, const SDLoc &DL, EVT VT)
Create negative operation as (SUB 0, Val).
LLVM_ABI void setNodeMemRefs(MachineSDNode *N, ArrayRef< MachineMemOperand * > NewMemRefs)
Mutate the specified machine node's memory references to the provided list.
LLVM_ABI SDValue getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT)
Return the expression required to zero extend the Op value assuming it was the smaller SrcTy value.
const DataLayout & getDataLayout() const
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI bool areNonVolatileConsecutiveStores(StoreSDNode *ST, StoreSDNode *Base, TypeSize Bytes, int Dist) const
Return true if stores are next to each other and can be merged.
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
SDValue getSignedTargetConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI void ReplaceAllUsesWith(SDValue From, SDValue To)
Modify anything using 'From' to use 'To' instead.
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI std::pair< SDValue, SDValue > SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the vector with EXTRACT_SUBVECTOR using the provided VTs and return the low/high part.
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
LLVM_ABI MaybeAlign InferPtrAlign(SDValue Ptr) const
Infer alignment of a load / store address.
SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize, const SDLoc &DL)
Return a new CALLSEQ_START node, that starts new call frame, in which InSize bytes are set up inside ...
LLVM_ABI SDValue getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand)
A convenience function for creating TargetInstrInfo::EXTRACT_SUBREG nodes.
LLVM_ABI SDValue getBasicBlock(MachineBasicBlock *MBB)
SDValue getSelectCC(const SDLoc &DL, SDValue LHS, SDValue RHS, SDValue True, SDValue False, ISD::CondCode Cond, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build SelectCC's if you just have an ISD::CondCode instead of an...
LLVM_ABI SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either sign-extending or trunca...
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI bool isKnownNeverZero(SDValue Op, unsigned Depth=0) const
Test whether the given SDValue is known to contain non-zero value(s).
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
const LibcallLoweringInfo & getLibcalls() const
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI OverflowKind computeOverflowForSignedAdd(SDValue N0, SDValue N1) const
Determine if the result of the signed addition of 2 nodes can overflow.
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI unsigned ComputeNumSignBits(SDValue Op, unsigned Depth=0) const
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI SDValue getVectorIdxConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
SDValue getPOISON(EVT VT)
Return a POISON node. POISON does not have a useful SDLoc.
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
LLVM_ABI SDValue getRegisterMask(const uint32_t *RegMask)
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVM_ABI SDValue getCondCode(ISD::CondCode Cond)
void addCallSiteInfo(const SDNode *Node, CallSiteInfo &&CallInfo)
Set CallSiteInfo to be associated with Node.
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, TypeSize Offset)
Create an add instruction with appropriate flags when used for addressing some offset of an object.
LLVMContext * getContext() const
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
LLVM_ABI SDValue CreateStackTemporary(TypeSize Bytes, Align Alignment)
Create a stack temporary based on the size in bytes and the alignment.
SDValue getTargetConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offset=0, unsigned TargetFlags=0)
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
LLVM_ABI SDValue getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Base, SDValue Offset, SDValue Mask, SDValue Src0, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, ISD::LoadExtType, bool IsExpanding=false)
DenormalMode getDenormalMode(EVT VT) const
Return the current function's default denormal handling kind for the given floating point type.
LLVM_ABI std::pair< SDValue, SDValue > SplitScalar(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the scalar node with EXTRACT_ELEMENT using the provided VTs and return the low/high part.
LLVM_ABI SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, ArrayRef< int > Mask)
Return an ISD::VECTOR_SHUFFLE node.
LLVM_ABI SDValue getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a logical NOT operation as (XOR Val, BooleanOne).
This instruction constructs a fixed permutation of two input vectors.
VectorType * getType() const
Overload to return most specific vector type.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
static LLVM_ABI bool isIdentityMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from exactly one source vector without lane crossin...
This SDNode is used to implement the code generator support for the llvm IR shufflevector instruction...
int getMaskElt(unsigned Idx) const
ArrayRef< int > getMask() const
static LLVM_ABI bool isSplatMask(ArrayRef< int > Mask)
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
bool empty() const
Definition SmallSet.h:169
bool erase(const T &V)
Definition SmallSet.h:200
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
size_type size() const
Definition SmallSet.h:171
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
iterator insert(iterator I, T &&Elt)
void resize(size_type N)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
This class is used to represent ISD::STORE nodes.
const SDValue & getBasePtr() const
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
const unsigned char * bytes_end() const
Definition StringRef.h:125
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
const unsigned char * bytes_begin() const
Definition StringRef.h:122
TargetInstrInfo - Interface to description of machine instruction set.
Provides information about what library functions are available for the current target.
bool isOperationExpand(unsigned Op, EVT VT) const
Return true if the specified operation is illegal on this target or unlikely to be made legal with cu...
void setBooleanVectorContents(BooleanContent Ty)
Specify how the target extends the result of a vector boolean value from a vector of i1 to a wider ty...
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action)
Indicate that the specified operation does not work with the specified type and indicate what to do a...
virtual void finalizeLowering(MachineFunction &MF) const
Execute target specific actions to finalize target lowering.
void setMaxDivRemBitWidthSupported(unsigned SizeInBits)
Set the size in bits of the maximum div/rem the backend supports.
bool PredictableSelectIsExpensive
Tells the code generator that select is more expensive than a branch if the branch is usually predict...
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
unsigned MaxStoresPerMemcpyOptSize
Likewise for functions with the OptSize attribute.
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
ShiftLegalizationStrategy
Return the preferred strategy to legalize tihs SHIFT instruction, with ExpansionFactor being the recu...
void setMinStackArgumentAlignment(Align Alignment)
Set the minimum stack alignment of an argument.
virtual Value * getIRStackGuard(IRBuilderBase &IRB, const LibcallLoweringInfo &Libcalls) const
If the target has a standard location for the stack protector guard, returns the address of that loca...
const TargetMachine & getTargetMachine() const
virtual void insertSSPDeclarations(Module &M, const LibcallLoweringInfo &Libcalls) const
Inserts necessary declarations for SSP (stack protection) purpose.
bool isFPImmLegal(const APFloat &Imm, EVT VT, bool ForCodeSize=false) const
Returns true if the specified FP immediate can be materialized without a load from the constant pool.
void setIndexedMaskedLoadAction(unsigned IdxMode, MVT VT, LegalizeAction Action)
Indicate that the specified indexed masked load does or does not work with the specified type and ind...
void setIndexedLoadAction(ArrayRef< unsigned > IdxModes, MVT VT, LegalizeAction Action)
Indicate that the specified indexed load does or does not work with the specified type and indicate w...
void setPrefLoopAlignment(Align Alignment)
Set the target's preferred loop alignment.
void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits)
Set the maximum atomic operation size supported by the backend.
Sched::Preference getSchedulingPreference() const
Return target scheduling preference.
void setMinFunctionAlignment(Align Alignment)
Set the target's minimum function alignment.
unsigned MaxStoresPerMemsetOptSize
Likewise for functions with the OptSize attribute.
void setBooleanContents(BooleanContent Ty)
Specify how the target extends the result of integer and floating point boolean values from i1 to a w...
unsigned MaxStoresPerMemmove
Specify maximum number of store instructions per memmove call.
void computeRegisterProperties(const TargetRegisterInfo *TRI)
Once all of the register classes are added, this allows us to compute derived properties we expose.
unsigned MaxStoresPerMemmoveOptSize
Likewise for functions with the OptSize attribute.
void addRegisterClass(MVT VT, const TargetRegisterClass *RC)
Add the specified register class as an available regclass for the specified value type.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
void setIndexedStoreAction(ArrayRef< unsigned > IdxModes, MVT VT, LegalizeAction Action)
Indicate that the specified indexed store does or does not work with the specified type and indicate ...
ExtractSubvectorCost
Enum that specifies how expensive lowering an EXTRACT_SUBVECTOR is.
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
void setPrefFunctionAlignment(Align Alignment)
Set the target's preferred function alignment.
virtual unsigned getMaxSupportedInterleaveFactor() const
Get the maximum supported factor for interleaved memory accesses.
void setIndexedMaskedStoreAction(unsigned IdxMode, MVT VT, LegalizeAction Action)
Indicate that the specified indexed masked store does or does not work with the specified type and in...
unsigned MaxStoresPerMemset
Specify maximum number of store instructions per memset call.
FPImmAction
How the legalizer should materialize a floating-point immediate.
@ ConstantPool
Load the immediate from the constant pool.
@ Legal
The target can instruction select the immediate natively.
@ Bitcast
Build the immediate as a bitcast of an integer constant with the same bits.
void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified truncating store does not work with the specified type and indicate what ...
virtual ShiftLegalizationStrategy preferredShiftLegalizationStrategy(SelectionDAG &DAG, SDNode *N, unsigned ExpansionFactor) const
bool isOperationLegalOrCustom(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
virtual bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *Fast=nullptr) const
Return true if the target supports a memory access of this type for the given address space and align...
void setStackPointerRegisterToSaveRestore(Register R)
If set to a physical register, this specifies the register that llvm.savestack/llvm....
void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT)
If Opc/OrigVT is specified as being promoted, the promotion code defaults to trying a larger integer/...
AtomicExpansionKind
Enum that specifies what an atomic load/AtomicRMWInst is expanded to, if at all.
virtual std::pair< const TargetRegisterClass *, uint8_t > findRepresentativeClass(const TargetRegisterInfo *TRI, MVT VT) const
Return the largest legal super-reg register class of the register class for the specified type and it...
RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Get the libcall impl routine name for the specified libcall.
static StringRef getLibcallImplName(RTLIB::LibcallImpl Call)
Get the libcall routine name for the specified libcall implementation.
void setTargetDAGCombine(ArrayRef< ISD::NodeType > NTs)
Targets should invoke this method for each target independent node that they want to provide a custom...
void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified load with extension does not work with the specified type and indicate wh...
LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const
Return how we should legalize values of this type, either it is already legal (return 'Legal') or we ...
std::vector< ArgListEntry > ArgListTy
unsigned MaxStoresPerMemcpy
Specify maximum number of store instructions per memcpy call.
void setSchedulingPreference(Sched::Preference Pref)
Specify the target scheduling preference.
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS, SDValue &NewRHS, ISD::CondCode &CCCode, const SDLoc &DL, const SDValue OldLHS, const SDValue OldRHS) const
Soften the operands of a comparison.
SDValue expandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG) const
Expands an unaligned store to 2 half-size stores for integer values, and possibly more for vectors.
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
bool parametersInCSRMatch(const MachineRegisterInfo &MRI, const uint32_t *CallerPreservedMask, const SmallVectorImpl< CCValAssign > &ArgLocs, const SmallVectorImpl< SDValue > &OutVals) const
Check whether parameters to a call that are passed in callee saved registers are the same as from the...
std::pair< SDValue, SDValue > expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const
Expands an unaligned load to 2 half-size loads for an integer, and possibly more for vectors.
virtual SDValue LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, SelectionDAG &DAG) const
Lower TLS global address SDNode for target independent emulated TLS model.
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
bool expandDIVREMByConstant(SDNode *N, SmallVectorImpl< SDValue > &Result, EVT HiLoVT, SelectionDAG &DAG, SDValue LL=SDValue(), SDValue LH=SDValue()) const
Attempt to expand an n-bit div/rem/divrem by constant using an n/2-bit algorithm.
bool isPositionIndependent() const
virtual ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const
Examine constraint string and operand type and determine a weight value.
SDValue buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0, SDValue N1, MutableArrayRef< int > Mask, SelectionDAG &DAG) const
Tries to build a legal vector shuffle using the provided parameters or equivalent variations.
static ArgListTy getArgListForFunctionType(FunctionType *FuncTy, const AttributeList &FuncAttrs, ArrayRef< SDValue > Ops)
Build a call argument list for FuncTy, taking the argument node values from Ops and the parameter typ...
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth=0, bool AssumeSingleUse=false) const
Look at Op.
virtual bool SimplifyDemandedBitsForTargetNode(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth=0) const
Attempt to simplify any target nodes based on the demanded bits/elts, returning true on success.
TargetLowering(const TargetLowering &)=delete
virtual ArrayRef< MCPhysReg > getRoundingControlRegisters() const
Returns a 0 terminated array of rounding control registers that can be attached into strict FP call.
virtual bool canCreateUndefOrPoisonForTargetNode(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, UndefPoisonKind Kind, bool ConsiderFlags, unsigned Depth) const
Return true if Op can create undef or poison from non-undef & non-poison operands.
virtual bool useLoadStackGuardNode(const Module &M) const
If this function returns true, SelectionDAGBuilder emits a LOAD_STACK_GUARD node when it is lowering ...
virtual void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const
Lower the specified operand into the Ops vector.
std::pair< SDValue, SDValue > makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl, EVT RetVT, ArrayRef< SDValue > Ops, MakeLibCallOptions CallOptions, const SDLoc &dl, SDValue Chain=SDValue()) const
Returns a pair of (return value, chain).
void setTypeIdForCallsiteInfo(const CallBase *CB, MachineFunction &MF, MachineFunction::CallSiteInfo &CSInfo) const
Primary interface to the complete machine description for the target machine.
TLSModel::Model getTLSModel(const GlobalValue *GV) const
Returns the TLS model which should be used for the given global variable.
const Triple & getTargetTriple() const
bool useEmulatedTLS() const
Returns true if this target uses emulated TLS.
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
TargetOptions Options
unsigned EnableFastISel
EnableFastISel - This flag enables fast-path instruction selection which trades away generated code q...
unsigned GuaranteedTailCallOpt
GuaranteedTailCallOpt - This flag is enabled when -tailcallopt is specified on the commandline.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
static LLVM_ABI IntegerType * getInt16Ty(LLVMContext &C)
Definition Type.cpp:293
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
Base class of all SIMD vector types.
Type * getElementType() const
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:183
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
IteratorT end() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
static CondCodes getOppositeCondition(CondCodes CC)
Definition ARMBaseInfo.h:49
static ARMCC::CondCodes getSwappedCondition(ARMCC::CondCodes CC)
getSwappedCondition - assume the flags are set by MI(a,b), return the condition code if we modify the...
Definition ARMBaseInfo.h:72
@ SECREL
Thread Pointer Offset.
@ GOT_PREL
Thread Local Storage (General Dynamic Mode)
@ SBREL
Section Relative (Windows TLS)
@ GOTTPOFF
Global Offset Table, PC Relative.
@ TPOFF
Global Offset Table, Thread Pointer Offset.
TOF
Target Operand Flag enum.
@ MO_NONLAZY
MO_NONLAZY - This is an independent flag, on a symbol operand "FOO" it represents a symbol which,...
@ MO_SBREL
MO_SBREL - On a symbol operand, this represents a static base relative relocation.
@ MO_DLLIMPORT
MO_DLLIMPORT - On a symbol operand, this represents that the reference to the symbol is for an import...
@ MO_GOT
MO_GOT - On a symbol operand, this represents a GOT relative relocation.
@ MO_COFFSTUB
MO_COFFSTUB - On a symbol operand "FOO", this indicates that the reference is actually to the "....
static ShiftOpc getShiftOpcForNode(unsigned Opcode)
int getSOImmVal(unsigned Arg)
getSOImmVal - Given a 32-bit immediate, if it is something that can fit into an shifter_operand immed...
int getFP32Imm(const APInt &Imm)
getFP32Imm - Return an 8-bit floating-point version of the 32-bit floating-point value.
uint64_t decodeVMOVModImm(unsigned ModImm, unsigned &EltBits)
decodeVMOVModImm - Decode a NEON/MVE modified immediate value into the element value and the element ...
unsigned getAM2Offset(unsigned AM2Opc)
bool isThumbImmShiftedVal(unsigned V)
isThumbImmShiftedVal - Return true if the specified value can be obtained by left shifting a 8-bit im...
int getT2SOImmVal(unsigned Arg)
getT2SOImmVal - Given a 32-bit immediate, if it is something that can fit into a Thumb-2 shifter_oper...
unsigned createVMOVModImm(unsigned OpCmode, unsigned Val)
int getFP64Imm(const APInt &Imm)
getFP64Imm - Return an 8-bit floating-point version of the 64-bit floating-point value.
int getFP16Imm(const APInt &Imm)
getFP16Imm - Return an 8-bit floating-point version of the 16-bit floating-point value.
unsigned getSORegOpc(ShiftOpc ShOp, unsigned Imm)
int getFP32FP16Imm(const APInt &Imm)
If this is a FP16Imm encoded as a fp32 value, return the 8-bit encoding for it.
AddrOpc getAM2Op(unsigned AM2Opc)
bool isBitFieldInvertedMask(unsigned v)
const unsigned FPStatusBits
FastISel * createFastISel(FunctionLoweringInfo &funcInfo, const TargetLibraryInfo *libInfo, const LibcallLoweringInfo *libcallLowering)
const unsigned FPReservedBits
const unsigned RoundingBitsPos
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ Swift
Calling convention for Swift.
Definition CallingConv.h:69
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
@ CFGuard_Check
Special calling convention on Windows for calling the Control Guard Check ICall funtion.
Definition CallingConv.h:82
@ PreserveMost
Used for runtime calls that preserves most registers.
Definition CallingConv.h:63
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
@ CXX_FAST_TLS
Used for access functions.
Definition CallingConv.h:72
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
Definition CallingConv.h:66
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
Definition CallingConv.h:87
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
LLVM_ABI bool isConstantSplatVector(SDValue V, APInt &SplatValue)
Node predicates.
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:43
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:851
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:263
@ STACKRESTORE
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain.
@ STACKSAVE
STACKSAVE - STACKSAVE has one operand, an input chain.
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:516
@ POISON
POISON - A poison node.
Definition ISDOpcodes.h:238
@ SET_FPENV
Sets the current floating-point environment.
@ MLOAD
Masked load and store - consecutive vector load and store operations with additional mask operand tha...
@ EH_SJLJ_LONGJMP
OUTCHAIN = EH_SJLJ_LONGJMP(INCHAIN, buffer) This corresponds to the eh.sjlj.longjmp intrinsic.
Definition ISDOpcodes.h:170
@ FGETSIGN
INT = FGETSIGN(FP) - Return the sign bit of the specified floating point value as an integer 0/1 valu...
Definition ISDOpcodes.h:543
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:277
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:605
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:811
@ VAEND
VAEND, VASTART - VAEND and VASTART have three operands: an input chain, pointer, and a SRCVALUE.
@ ATOMIC_STORE
OUTCHAIN = ATOMIC_STORE(INCHAIN, val, ptr) This corresponds to "store atomic" instruction.
@ RESET_FPENV
Set floating-point environment to default state.
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ SET_FPMODE
Sets the current dynamic floating-point control modes.
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:885
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:523
@ FMODF
FMODF - Decomposes the operand into integral and fractional parts, each having the same type and sign...
@ FATAN2
FATAN2 - atan2, inspired by libm.
@ FSINCOSPI
FSINCOSPI - Compute both the sine and cosine times pi more accurately than FSINCOS(pi*x),...
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:222
@ EH_SJLJ_SETUP_DISPATCH
OUTCHAIN = EH_SJLJ_SETUP_DISPATCH(INCHAIN) The target initializes the dispatch table here.
Definition ISDOpcodes.h:174
@ GlobalAddress
Definition ISDOpcodes.h:90
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:912
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:589
@ VECREDUCE_FMAX
FMIN/FMAX nodes can have flags, for NaN/NoNaN variants.
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:771
@ ATOMIC_FENCE
OUTCHAIN = ATOMIC_FENCE(INCHAIN, ordering, scope) This corresponds to the fence instruction.
@ RESET_FPMODE
Sets default dynamic floating-point control modes.
@ SDIVREM
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition ISDOpcodes.h:282
@ FP16_TO_FP
FP16_TO_FP, FP_TO_FP16 - These operators are used to perform promotions and truncation for half-preci...
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:256
@ FLDEXP
FLDEXP - ldexp, inspired by libm (op0 * 2**op1).
@ STRICT_FSQRT
Constrained versions of libm-equivalent floating point intrinsics.
Definition ISDOpcodes.h:441
@ BUILTIN_OP_END
BUILTIN_OP_END - This must be the last enum value in this list.
@ GlobalTLSAddress
Definition ISDOpcodes.h:91
@ CTLZ_ZERO_POISON
Definition ISDOpcodes.h:820
@ SET_ROUNDING
Set rounding mode.
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:876
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:731
@ STRICT_UINT_TO_FP
Definition ISDOpcodes.h:490
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:681
@ BR
Control flow instructions. These all have token chains.
@ VECREDUCE_FADD
These reductions have relaxed evaluation order semantics, and have a single vector operand.
@ PREFETCH
PREFETCH - This corresponds to a prefetch intrinsic.
@ FSINCOS
FSINCOS - Compute both fsin and fcos as a single operation.
@ SETCCCARRY
Like SetCC, ops #0 and #1 are the LHS and RHS operands to compare, but op #2 is a boolean indicating ...
Definition ISDOpcodes.h:859
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ BR_CC
BR_CC - Conditional branch.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:355
@ BR_JT
BR_JT - Jumptable branch.
@ VECTOR_INTERLEAVE
VECTOR_INTERLEAVE(VEC1, VEC2, ...) - Returns N vectors from N input vectors, where N is the factor to...
Definition ISDOpcodes.h:640
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:377
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:828
@ ATOMIC_LOAD
Val, OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr) This corresponds to "load atomic" instruction.
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:235
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:249
@ VACOPY
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer,...
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:232
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:351
@ CTLS
Count leading redundant sign bits.
Definition ISDOpcodes.h:824
@ VECREDUCE_ADD
Integer reductions may have a result type larger than the vector element type.
@ GET_ROUNDING
Returns current rounding mode: -1 Undefined 0 Round to 0 1 Round to nearest, ties to even 2 Round to ...
@ STRICT_FP_TO_FP16
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:720
@ GET_FPMODE
Reads the current dynamic floating-point control modes.
@ STRICT_FP16_TO_FP
@ GET_FPENV
Gets the current floating-point environment.
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:793
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:659
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:619
@ READ_REGISTER
READ_REGISTER, WRITE_REGISTER - This node represents llvm.register on the DAG, which implements the n...
Definition ISDOpcodes.h:141
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:581
@ CopyToReg
CopyToReg - This node has three operands: a chain, a register number to set to this value,...
Definition ISDOpcodes.h:226
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:882
@ DEBUGTRAP
DEBUGTRAP - Trap intended to get the attention of a debugger.
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:843
@ ATOMIC_CMP_SWAP
Val, OUTCHAIN = ATOMIC_CMP_SWAP(INCHAIN, ptr, cmp, swap) For double-word atomic operations: ValLo,...
@ FMINNUM
FMINNUM/FMAXNUM - Same semantics as the llvm.minnum/maxnum intrinsics.
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:359
@ DYNAMIC_STACKALLOC
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary.
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:920
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:751
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:837
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:331
@ STRICT_SINT_TO_FP
STRICT_[US]INT_TO_FP - Convert a signed or unsigned integer to a floating point value.
Definition ISDOpcodes.h:489
@ STRICT_FROUNDEVEN
Definition ISDOpcodes.h:469
@ BF16_TO_FP
BF16_TO_FP, FP_TO_BF16 - These operators are used to perform promotions and truncation for bfloat16.
@ FRAMEADDR
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG.
Definition ISDOpcodes.h:112
@ STRICT_FP_TO_UINT
Definition ISDOpcodes.h:483
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:505
@ STRICT_FP_TO_SINT
STRICT_FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:482
@ FMINIMUM
FMINIMUM/FMAXIMUM - Same semantics as the llvm.minimum/maximum intrinsics.
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:958
@ READCYCLECOUNTER
READCYCLECOUNTER - This corresponds to the readcyclecounter intrinsic.
@ STRICT_FP_EXTEND
X = STRICT_FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:510
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:763
@ TRAP
TRAP - Trapping instruction.
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:207
@ SCMP
[US]CMP - 3-way comparison of signed or unsigned integers.
Definition ISDOpcodes.h:759
@ AVGFLOORS
AVGFLOORS/AVGFLOORU - Averaging add - Add two integers using an integer of type i[N+1],...
Definition ISDOpcodes.h:726
@ STRICT_FADD
Constrained versions of the binary floating point operators.
Definition ISDOpcodes.h:430
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:570
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ ATOMIC_SWAP
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN,...
@ CTTZ_ZERO_POISON
Bit counting operators with a poisoned result for zero inputs.
Definition ISDOpcodes.h:819
@ FFREXP
FFREXP - frexp, extract fractional and exponent component of a floating-point value.
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:991
@ SPONENTRY
SPONENTRY - Represents the llvm.sponentry intrinsic.
Definition ISDOpcodes.h:124
@ STRICT_FNEARBYINT
Definition ISDOpcodes.h:461
@ FP_TO_SINT_SAT
FP_TO_[US]INT_SAT - Convert floating point value in operand 0 to a signed or unsigned scalar integer ...
Definition ISDOpcodes.h:977
@ EH_SJLJ_SETJMP
RESULT, OUTCHAIN = EH_SJLJ_SETJMP(INCHAIN, buffer) This corresponds to the eh.sjlj....
Definition ISDOpcodes.h:164
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:888
@ VAARG
VAARG - VAARG has four operands: an input chain, a pointer, a SRCVALUE, and the alignment.
@ BRCOND
BRCOND - Conditional branch.
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:865
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:539
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:368
@ VECTOR_DEINTERLEAVE
VECTOR_DEINTERLEAVE(VEC1, VEC2, ...) - Returns N vectors from N input vectors, where N is the factor ...
Definition ISDOpcodes.h:629
@ ABDS
ABDS/ABDU - Absolute difference - Return the absolute difference between two numbers interpreted as s...
Definition ISDOpcodes.h:746
@ SADDO_CARRY
Carry-using overflow-aware nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:341
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:215
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:561
bool isNormalStore(const SDNode *N)
Returns true if the specified node is a non-truncating and unindexed store.
bool isZEXTLoad(const SDNode *N)
Returns true if the specified node is a ZEXTLOAD.
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, EVT Type)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
bool isEXTLoad(const SDNode *N)
Returns true if the specified node is a EXTLOAD.
LLVM_ABI CondCode getSetCCSwappedOperands(CondCode Operation)
Return the operation corresponding to (Y op X) when given the operation for (X op Y).
bool isSignedIntSetCC(CondCode Code)
Return true if this is a setcc instruction that performs a signed comparison when used with integer o...
LLVM_ABI bool isBuildVectorAllZeros(SDValue V)
Return true if the specified value is a BUILD_VECTOR where all of the elements are 0 or undef.
MemIndexedMode
MemIndexedMode enum - This enum defines the load / store indexed addressing modes.
bool isSEXTLoad(const SDNode *N)
Returns true if the specified node is a SEXTLOAD.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
static const int LAST_INDEXED_MODE
bool isNormalLoad(const SDNode *N)
Returns true if the specified node is a non-extending and unindexed load.
bool isIntEqualitySetCC(CondCode Code)
Return true if this is a setcc instruction that performs an equality comparison when used with intege...
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
constexpr MCPhysReg SP
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
auto m_Value()
Match an arbitrary value and ignore it.
LLVM_ABI Libcall getSINTTOFP(EVT OpVT, EVT RetVT)
getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getUINTTOFP(EVT OpVT, EVT RetVT)
getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getFPTOUINT(EVT OpVT, EVT RetVT)
getFPTOUINT - Return the FPTOUINT_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getFPTOSINT(EVT OpVT, EVT RetVT)
getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getFPEXT(EVT OpVT, EVT RetVT)
getFPEXT - Return the FPEXT_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getFPROUND(EVT OpVT, EVT RetVT)
getFPROUND - Return the FPROUND_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
bool sd_match(SDValue N, Pattern &&P)
ConstantInt_match m_ConstInt()
Match any integer constants or splat of an integer constant.
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
Definition LLVMContext.h:63
initializer< Ty > init(const Ty &Val)
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
bool RetFastCC_ARM_APCS(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
void stable_sort(R &&Range)
Definition STLExtras.h:2132
bool isVTRN_v_undef_Mask(ArrayRef< int > M, EVT VT, unsigned &WhichResult)
isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of "vector_shuffle v,...
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
bool HasLowerConstantMaterializationCost(unsigned Val1, unsigned Val2, const ARMSubtarget *Subtarget, bool ForCodesize=false)
Returns true if Val1 has a lower Constant Materialization Cost than Val2.
bool isVZIPMask(ArrayRef< int > M, EVT VT, unsigned &WhichResult)
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
InstructionCost Cost
LLVM_ABI bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
@ Known
Known to have no common set bits.
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Dead
Unused definition.
@ Kill
The last use of a register.
@ Define
Register definition.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition bit.h:315
bool CCAssignFn(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
CCAssignFn - This function assigns a location for Val, updating State to reflect the change.
bool CC_ARM_AAPCS(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
constexpr bool isMask_32(uint32_t Value)
Return true if the argument is a non-empty sequence of ones starting at the least significant bit wit...
Definition MathExtras.h:256
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
bool RetCC_ARM_AAPCS_VFP(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
bool RetCC_ARM_APCS(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:325
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
bool RetCC_ARM_AAPCS(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
LLVM_ABI Value * concatenateVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vecs)
Concatenate a list of vectors.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
void shuffle(Iterator first, Iterator last, RNG &&g)
Definition STLExtras.h:1546
bool CC_ARM_APCS_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
static std::array< MachineOperand, 2 > predOps(ARMCC::CondCodes Pred, unsigned PredReg=0)
Get the operands corresponding to the given Pred value.
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
constexpr bool isShiftedMask_32(uint32_t Value)
Return true if the argument contains a non-empty sequence of ones with the remainder zero (32 bit ver...
Definition MathExtras.h:268
LLVM_ABI ConstantFPSDNode * isConstOrConstSplatFP(SDValue N, bool AllowUndefs=false)
Returns the SDNode if it is a constant splat BuildVector or constant float.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
bool isReleaseOrStronger(AtomicOrdering AO)
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
constexpr bool has_single_bit(T Value) noexcept
Definition bit.h:149
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
LLVM_ABI bool isBitwiseNot(SDValue V, bool AllowUndefs=false)
Returns true if V is a bitwise not operation.
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
bool FastCC_ARM_APCS(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool CC_ARM_Win32_CFGuard_Check(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isVUZPMask(ArrayRef< int > M, EVT VT, unsigned &WhichResult)
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
bool isVTRNMask(ArrayRef< int > M, EVT VT, unsigned &WhichResult)
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
const unsigned PerfectShuffleTable[6561+1]
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Other
Any other memory.
Definition ModRef.h:68
CombineLevel
Definition DAGCombine.h:15
@ BeforeLegalizeTypes
Definition DAGCombine.h:16
@ AfterLegalizeTypes
Definition DAGCombine.h:17
unsigned ConstantMaterializationCost(unsigned Val, const ARMSubtarget *Subtarget, bool ForCodesize=false)
Returns the number of instructions required to materialize the given constant in a register,...
@ Mul
Product of integers.
@ And
Bitwise or logical AND of integers.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ FAdd
Sum of floats.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
@ Fast
Assign the register banks as fast as possible (default).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
bool isVUZP_v_undef_Mask(ArrayRef< int > M, EVT VT, unsigned &WhichResult)
isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of "vector_shuffle v,...
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI ConstantSDNode * isConstOrConstSplat(SDValue N, bool AllowUndefs=false, bool AllowTruncation=false)
Returns the SDNode if it is a constant splat BuildVector or constant int.
constexpr U AbsoluteValue(T X)
Return the absolute value of a signed integer, converted to the corresponding unsigned integer type.
Definition MathExtras.h:592
bool isAcquireOrStronger(AtomicOrdering AO)
constexpr unsigned BitWidth
ExceptionHandling
Definition CodeGen.h:54
@ SjLj
setjmp/longjmp based exceptions
Definition CodeGen.h:58
static MachineOperand t1CondCodeOp(bool isDead=false)
Get the operand corresponding to the conditional code result for Thumb1.
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
LLVM_ABI bool isOneConstant(SDValue V)
Returns true if V is a constant integer one.
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:249
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
static MachineOperand condCodeOp(unsigned CCReg=0)
Get the operand corresponding to the conditional code result.
bool isVREVMask(ArrayRef< int > M, EVT VT, unsigned BlockSize)
isVREVMask - Check if a vector shuffle corresponds to a VREV instruction with the specified blocksize...
unsigned gettBLXrOpcode(const MachineFunction &MF)
bool CC_ARM_APCS(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
@ Increment
Incrementally increasing token ID.
Definition AllocToken.h:26
bool CC_ARM_AAPCS_VFP(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
LLVM_ABI llvm::SmallVector< int, 16 > createSequentialMask(unsigned Start, unsigned NumInts, unsigned NumUndefs)
Create a sequential shuffle mask.
constexpr bool isShiftedUInt(uint64_t x)
Checks if a unsigned integer is an N bit number shifted left by S.
Definition MathExtras.h:199
unsigned convertAddSubFlagsOpcode(unsigned OldOpc)
Map pseudo instructions that imply an 'S' bit onto real opcodes.
LLVM_ABI bool isAllOnesConstant(SDValue V)
Returns true if V is an integer constant with all bits set.
bool isVZIP_v_undef_Mask(ArrayRef< int > M, EVT VT, unsigned &WhichResult)
isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of "vector_shuffle v,...
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
Load/store instruction that can be merged with a base address update.
SDNode * N
Instruction that updates a pointer.
unsigned ConstInc
Pointer increment value if it is a constant, or 0 otherwise.
SDValue Inc
Pointer increment operand.
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:775
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
static constexpr Align fromLog2(unsigned Log2Value)
Returns an alignment of 1 << Log2Value bytes.
Definition Alignment.h:73
static constexpr DenormalMode getIEEE()
Extended Value Type.
Definition ValueTypes.h:35
EVT changeVectorElementTypeToInteger() const
Return a vector with the same number of elements as this vector, but with the element type converted ...
Definition ValueTypes.h:90
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:160
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
uint64_t getScalarStoreSize() const
Definition ValueTypes.h:440
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:322
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:338
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:170
ElementCount getVectorElementCount() const
Definition ValueTypes.h:388
EVT getDoubleNumVectorElementsVT(LLVMContext &Context) const
Definition ValueTypes.h:509
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
unsigned getVectorMinNumElements() const
Given a vector type, return the minimum number of elements it contains.
Definition ValueTypes.h:397
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:423
bool isPow2VectorType() const
Returns true if the given vector is a power of 2.
Definition ValueTypes.h:516
static LLVM_ABI EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
EVT changeVectorElementType(LLVMContext &Context, EVT EltVT) const
Return a VT for a vector type whose attributes match ourselves with the exception of the element type...
Definition ValueTypes.h:98
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:354
bool is128BitVector() const
Return true if this is a 128-bit vector type.
Definition ValueTypes.h:245
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
Definition ValueTypes.h:419
bool isFixedLengthVector() const
Definition ValueTypes.h:214
static EVT getFloatingPointVT(unsigned BitWidth)
Returns the EVT that represents a floating-point type with the given number of bits.
Definition ValueTypes.h:55
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:191
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:361
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:366
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:180
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:374
bool bitsLE(EVT VT) const
Return true if this has no more bits than VT.
Definition ValueTypes.h:346
EVT getHalfNumVectorElementsVT(LLVMContext &Context) const
Definition ValueTypes.h:499
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:175
bool is64BitVector() const
Return true if this is a 64-bit vector type.
Definition ValueTypes.h:240
InputArg - This struct carries flags and type information about a single incoming (formal) argument o...
EVT ArgVT
Usually the non-legalized type of the argument, which is the EVT corresponding to the OrigTy IR type.
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
KnownBits zext(unsigned BitWidth) const
Return known bits for a zero extension of the value we're tracking.
Definition KnownBits.h:176
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
Definition KnownBits.h:325
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
APInt getSignedMinValue() const
Return the minimal signed value possible given these KnownBits.
Definition KnownBits.h:136
Matching combinators.
SmallVector< ArgRegPair, 1 > ArgRegPairs
Vector of call argument and its forwarding register.
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getJumpTable(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a jump table entry.
static LLVM_ABI MachinePointerInfo getStack(MachineFunction &MF, int64_t Offset, uint8_t ID=0)
Stack pointer relative access.
static LLVM_ABI MachinePointerInfo getConstantPool(MachineFunction &MF)
Return a MachinePointerInfo record that refers to the constant pool.
static LLVM_ABI MachinePointerInfo getGOT(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a GOT entry.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
A simple container for information about the supported runtime calls.
LLVM_ABI FunctionCallee getOrInsertLibcallDecl(Module &M, RTLIB::LibcallImpl LibcallImpl) const
LLVM_ABI GlobalValue * getOrInsertImplGlobal(Module &M, RTLIB::LibcallImpl LibcallImpl) const
LLVM_ABI std::pair< FunctionType *, AttributeList > getFunctionTy(LLVMContext &Ctx, const Triple &TT, const DataLayout &DL, RTLIB::LibcallImpl LibcallImpl) const
These are IR-level optimization flags that may be propagated to SDNodes.
bool hasNoSignedZeros() const
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg + ScalableOffset*...
This contains information for each constraint that we are lowering.
This structure contains all information that is necessary for lowering calls.
CallLoweringInfo & setInRegister(bool Value=true)
CallLoweringInfo & setLibCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList)
SmallVector< ISD::InputArg, 32 > Ins
CallLoweringInfo & setZExtResult(bool Value=true)
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
CallLoweringInfo & setSExtResult(bool Value=true)
SmallVector< ISD::OutputArg, 32 > Outs
CallLoweringInfo & setChain(SDValue InChain)
CallLoweringInfo & setCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList, AttributeSet ResultAttrs={})
LLVM_ABI void AddToWorklist(SDNode *N)
LLVM_ABI bool recursivelyDeleteUnusedNodes(SDNode *N)
LLVM_ABI SDValue CombineTo(SDNode *N, ArrayRef< SDValue > To, bool AddTo=true)
This structure is used to pass arguments to makeLibCall function.
A convenience struct that encapsulates a DAG, and two SDValues for returning information from TargetL...