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"
66#include "llvm/IR/Attributes.h"
67#include "llvm/IR/CallingConv.h"
68#include "llvm/IR/Constant.h"
69#include "llvm/IR/Constants.h"
70#include "llvm/IR/DataLayout.h"
71#include "llvm/IR/DebugLoc.h"
73#include "llvm/IR/Function.h"
74#include "llvm/IR/GlobalAlias.h"
75#include "llvm/IR/GlobalValue.h"
77#include "llvm/IR/IRBuilder.h"
78#include "llvm/IR/InlineAsm.h"
79#include "llvm/IR/Instruction.h"
82#include "llvm/IR/Intrinsics.h"
83#include "llvm/IR/IntrinsicsARM.h"
84#include "llvm/IR/Module.h"
85#include "llvm/IR/Type.h"
86#include "llvm/IR/User.h"
87#include "llvm/IR/Value.h"
88#include "llvm/MC/MCInstrDesc.h"
90#include "llvm/MC/MCSchedule.h"
97#include "llvm/Support/Debug.h"
105#include <algorithm>
106#include <cassert>
107#include <cstdint>
108#include <cstdlib>
109#include <iterator>
110#include <limits>
111#include <optional>
112#include <tuple>
113#include <utility>
114#include <vector>
115
116using namespace llvm;
117
118#define DEBUG_TYPE "arm-isel"
119
120STATISTIC(NumTailCalls, "Number of tail calls");
121STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
122STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
123STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
124STATISTIC(NumConstpoolPromoted,
125 "Number of constants with their storage promoted into constant pools");
126
127static cl::opt<bool>
128ARMInterworking("arm-interworking", cl::Hidden,
129 cl::desc("Enable / disable ARM interworking (for debugging only)"),
130 cl::init(true));
131
133 "arm-promote-constant", cl::Hidden,
134 cl::desc("Enable / disable promotion of unnamed_addr constants into "
135 "constant pools"),
136 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
138 "arm-promote-constant-max-size", cl::Hidden,
139 cl::desc("Maximum size of constant to promote into a constant pool"),
140 cl::init(64));
142 "arm-promote-constant-max-total", cl::Hidden,
143 cl::desc("Maximum size of ALL constants to promote into a constant pool"),
144 cl::init(128));
145
147MVEMaxSupportedInterleaveFactor("mve-max-interleave-factor", cl::Hidden,
148 cl::desc("Maximum interleave factor for MVE VLDn to generate."),
149 cl::init(2));
150
152 "arm-max-base-updates-to-check", cl::Hidden,
153 cl::desc("Maximum number of base-updates to check generating postindex."),
154 cl::init(64));
155
156/// Value type used for "flags" operands / results (either CPSR or FPSCR_NZCV).
157constexpr MVT FlagsVT = MVT::i32;
158
159// The APCS parameter registers.
160static const MCPhysReg GPRArgRegs[] = {
161 ARM::R0, ARM::R1, ARM::R2, ARM::R3
162};
163
165 SelectionDAG &DAG, const SDLoc &DL) {
167 assert(Arg.ArgVT.bitsLT(MVT::i32));
168 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, Arg.ArgVT, Value);
169 SDValue Ext =
171 MVT::i32, Trunc);
172 return Ext;
173}
174
175void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT) {
176 if (VT != PromotedLdStVT) {
178 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
179
181 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
182 }
183
184 MVT ElemTy = VT.getVectorElementType();
185 if (ElemTy != MVT::f64)
189 if (ElemTy == MVT::i32) {
194 } else {
199 }
208 if (VT.isInteger()) {
212 }
213
214 // Neon does not support vector divide/remainder operations.
223
224 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
225 for (auto Opcode : {ISD::ABS, ISD::ABDS, ISD::ABDU, ISD::SMIN, ISD::SMAX,
227 setOperationAction(Opcode, VT, Legal);
228 if (!VT.isFloatingPoint())
229 for (auto Opcode : {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT})
230 setOperationAction(Opcode, VT, Legal);
231}
232
233void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
234 addRegisterClass(VT, &ARM::DPRRegClass);
235 addTypeForNEON(VT, MVT::f64);
236}
237
238void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
239 addRegisterClass(VT, &ARM::DPairRegClass);
240 addTypeForNEON(VT, MVT::v2f64);
241}
242
243void ARMTargetLowering::setAllExpand(MVT VT) {
244 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
246
247 // We support these really simple operations even on types where all
248 // the actual arithmetic has to be broken down into simpler
249 // operations or turned into library calls.
254}
255
256void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To,
257 LegalizeAction Action) {
258 setLoadExtAction(ISD::EXTLOAD, From, To, Action);
259 setLoadExtAction(ISD::ZEXTLOAD, From, To, Action);
260 setLoadExtAction(ISD::SEXTLOAD, From, To, Action);
261}
262
263void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) {
264 const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 };
265
266 for (auto VT : IntTypes) {
267 addRegisterClass(VT, &ARM::MQPRRegClass);
298
299 // No native support for these.
309
310 // Vector reductions
320
321 if (!HasMVEFP) {
326 } else {
329 }
330
331 // Pre and Post inc are supported on loads and stores
332 for (unsigned im = (unsigned)ISD::PRE_INC;
333 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
338 }
339 }
340
341 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
342 for (auto VT : FloatTypes) {
343 addRegisterClass(VT, &ARM::MQPRRegClass);
344 if (!HasMVEFP)
345 setAllExpand(VT);
346
347 // These are legal or custom whether we have MVE.fp or not
360
361 // Pre and Post inc are supported on loads and stores
362 for (unsigned im = (unsigned)ISD::PRE_INC;
363 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
368 }
369
370 if (HasMVEFP) {
378 }
383
384 // No native support for these.
399 }
400 }
401
402 // Custom Expand smaller than legal vector reductions to prevent false zero
403 // items being added.
412
413 // We 'support' these types up to bitcast/load/store level, regardless of
414 // MVE integer-only / float support. Only doing FP data processing on the FP
415 // vector types is inhibited at integer-only level.
416 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
417 for (auto VT : LongTypes) {
418 addRegisterClass(VT, &ARM::MQPRRegClass);
419 setAllExpand(VT);
425 }
427
428 // We can do bitwise operations on v2i64 vectors
429 setOperationAction(ISD::AND, MVT::v2i64, Legal);
430 setOperationAction(ISD::OR, MVT::v2i64, Legal);
431 setOperationAction(ISD::XOR, MVT::v2i64, Legal);
432
433 // It is legal to extload from v4i8 to v4i16 or v4i32.
434 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
435 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
436 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
437
438 // It is legal to sign extend from v4i8/v4i16 to v4i32 or v8i8 to v8i16.
444
445 // Some truncating stores are legal too.
446 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
447 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
448 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
449
450 // Pre and Post inc on these are legal, given the correct extends
451 for (unsigned im = (unsigned)ISD::PRE_INC;
452 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
453 for (auto VT : {MVT::v8i8, MVT::v4i8, MVT::v4i16}) {
458 }
459 }
460
461 // Predicate types
462 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1, MVT::v2i1};
463 for (auto VT : pTypes) {
464 addRegisterClass(VT, &ARM::VCCRRegClass);
479
480 if (!HasMVEFP) {
485 }
486 }
490 setOperationAction(ISD::OR, MVT::v2i1, Expand);
496
505}
506
508 return static_cast<const ARMBaseTargetMachine &>(getTargetMachine());
509}
510
512 const ARMSubtarget &STI)
513 : TargetLowering(TM_, STI), Subtarget(&STI),
514 RegInfo(Subtarget->getRegisterInfo()),
515 Itins(Subtarget->getInstrItineraryData()) {
516 const auto &TM = static_cast<const ARMBaseTargetMachine &>(TM_);
517
520
521 const Triple &TT = TM.getTargetTriple();
522
523 if (Subtarget->isThumb1Only())
524 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
525 else
526 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
527
528 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
529 Subtarget->hasFPRegs()) {
530 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
531 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
532
533 if (!Subtarget->hasVFP2Base()) {
534 setAllExpand(MVT::f32);
535 } else {
538
541 setOperationAction(Op, MVT::f32, Legal);
542 }
543 if (!Subtarget->hasFP64()) {
544 setAllExpand(MVT::f64);
545 } else {
548 setOperationAction(Op, MVT::f64, Legal);
549
551 }
552 }
553
554 if (Subtarget->hasFullFP16()) {
557 setOperationAction(Op, MVT::f16, Legal);
558
559 addRegisterClass(MVT::f16, &ARM::HPRRegClass);
562
567 }
568
569 if (Subtarget->hasBF16()) {
570 addRegisterClass(MVT::bf16, &ARM::HPRRegClass);
571 setAllExpand(MVT::bf16);
572 if (!Subtarget->hasFullFP16())
576 } else {
581 }
582
584 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
585 setTruncStoreAction(VT, InnerVT, Expand);
586 addAllExtLoads(VT, InnerVT, Expand);
587 }
588
591
593 }
594
595 if (!Subtarget->isThumb1Only() && !Subtarget->hasV8_1MMainlineOps())
597
598 if (!Subtarget->hasV8_1MMainlineOps())
600
601 if (!Subtarget->isThumb1Only())
603
606
609
610 if (Subtarget->hasMVEIntegerOps())
611 addMVEVectorTypes(Subtarget->hasMVEFloatOps());
612
613 // Combine low-overhead loop intrinsics so that we can lower i1 types.
614 if (Subtarget->hasLOB()) {
616 }
617
618 if (Subtarget->hasNEON()) {
619 addDRTypeForNEON(MVT::v2f32);
620 addDRTypeForNEON(MVT::v8i8);
621 addDRTypeForNEON(MVT::v4i16);
622 addDRTypeForNEON(MVT::v2i32);
623 addDRTypeForNEON(MVT::v1i64);
624
625 addQRTypeForNEON(MVT::v4f32);
626 addQRTypeForNEON(MVT::v2f64);
627 addQRTypeForNEON(MVT::v16i8);
628 addQRTypeForNEON(MVT::v8i16);
629 addQRTypeForNEON(MVT::v4i32);
630 addQRTypeForNEON(MVT::v2i64);
631
632 if (Subtarget->hasFullFP16()) {
633 addQRTypeForNEON(MVT::v8f16);
634 addDRTypeForNEON(MVT::v4f16);
635 }
636
637 if (Subtarget->hasBF16()) {
638 addQRTypeForNEON(MVT::v8bf16);
639 addDRTypeForNEON(MVT::v4bf16);
640 }
641 }
642
643 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
644 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
645 // none of Neon, MVE or VFP supports any arithmetic operations on it.
646 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
647 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
648 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
649 // FIXME: Code duplication: FDIV and FREM are expanded always, see
650 // ARMTargetLowering::addTypeForNEON method for details.
651 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
652 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
653 // FIXME: Create unittest.
654 // In another words, find a way when "copysign" appears in DAG with vector
655 // operands.
657 // FIXME: Code duplication: SETCC has custom operation action, see
658 // ARMTargetLowering::addTypeForNEON method for details.
660 // FIXME: Create unittest for FNEG and for FABS.
661 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
662 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
664 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
665 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
666 setOperationAction(ISD::FTAN, MVT::v2f64, Expand);
667 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
668 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
671 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
680 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
681 }
682
683 if (Subtarget->hasNEON()) {
684 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
685 // supported for v4f32.
687 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
688 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
689 setOperationAction(ISD::FTAN, MVT::v4f32, Expand);
690 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
691 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
694 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
703
704 // Mark v2f32 intrinsics.
706 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
707 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
708 setOperationAction(ISD::FTAN, MVT::v2f32, Expand);
709 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
710 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
713 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
722
725 setOperationAction(Op, MVT::v4f16, Expand);
726 setOperationAction(Op, MVT::v8f16, Expand);
727 }
728
729 // Neon does not support some operations on v1i64 and v2i64 types.
730 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
731 // Custom handling for some quad-vector types to detect VMULL.
732 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
733 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
734 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
735 // Custom handling for some vector types to avoid expensive expansions
736 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
738 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
740 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
741 // a destination type that is wider than the source, and nor does
742 // it have a FP_TO_[SU]INT instruction with a narrower destination than
743 // source.
752
755
756 // NEON does not have single instruction CTPOP for vectors with element
757 // types wider than 8-bits. However, custom lowering can leverage the
758 // v8i8/v16i8 vcnt instruction.
765
766 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
767 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
768
769 // NEON does not have single instruction CTTZ for vectors.
771 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
772 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
773 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
774
775 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
776 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
777 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
778 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
779
784
789
793 }
794
795 // NEON only has FMA instructions as of VFP4.
796 if (!Subtarget->hasVFP4Base()) {
797 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
798 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
799 }
800
803
804 // It is legal to extload from v4i8 to v4i16 or v4i32.
805 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
806 MVT::v2i32}) {
811 }
812 }
813
814 for (auto VT : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v16i8, MVT::v8i16,
815 MVT::v4i32}) {
820 }
821 }
822
823 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
830 }
831 if (Subtarget->hasMVEIntegerOps()) {
834 ISD::SETCC});
835 }
836 if (Subtarget->hasMVEFloatOps()) {
838 }
839
840 if (!Subtarget->hasFP64()) {
841 // When targeting a floating-point unit with only single-precision
842 // operations, f64 is legal for the few double-precision instructions which
843 // are present However, no double-precision operations other than moves,
844 // loads and stores are provided by the hardware.
881 }
882
883 // STRICT_(U/S)INT_TO_FP specifically use the input MVT to register with
884 // setOperationAction() as opposed to other opcodes that use the output MVT
885 // All inputs should be i32 due to type legalization
888
891
892 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
895 if (Subtarget->hasFullFP16()) {
898 }
899 } else {
901 }
902
903 if (!Subtarget->hasFP16()) {
906 } else {
909 }
910
911 computeRegisterProperties(Subtarget->getRegisterInfo());
912
913 // ARM does not have floating-point extending loads.
914 for (MVT VT : MVT::fp_valuetypes()) {
915 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
916 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
917 setLoadExtAction(ISD::EXTLOAD, VT, MVT::bf16, Expand);
918 }
919
920 // ... or truncating stores
921 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
922 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
923 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
924 setTruncStoreAction(MVT::f32, MVT::bf16, Expand);
925 setTruncStoreAction(MVT::f64, MVT::bf16, Expand);
926
927 // ARM does not have i1 sign extending load.
928 for (MVT VT : MVT::integer_valuetypes())
930
931 // ARM supports all 4 flavors of integer indexed load / store.
932 if (!Subtarget->isThumb1Only()) {
933 for (unsigned im = (unsigned)ISD::PRE_INC;
935 setIndexedLoadAction(im, MVT::i1, Legal);
936 setIndexedLoadAction(im, MVT::i8, Legal);
937 setIndexedLoadAction(im, MVT::i16, Legal);
938 setIndexedLoadAction(im, MVT::i32, Legal);
939 setIndexedStoreAction(im, MVT::i1, Legal);
940 setIndexedStoreAction(im, MVT::i8, Legal);
941 setIndexedStoreAction(im, MVT::i16, Legal);
942 setIndexedStoreAction(im, MVT::i32, Legal);
943 }
944 } else {
945 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
948 }
949
950 // Custom loads/stores to possible use __aeabi_uread/write*
951 if (TT.isTargetAEABI() && !Subtarget->allowsUnalignedMem()) {
956 }
957
962
963 if (!Subtarget->isThumb1Only()) {
966 }
967
972 if (Subtarget->hasDSP()) {
981 }
982 if (Subtarget->hasBaseDSP()) {
985 }
986
987 // i64 operation support.
990 if (Subtarget->isThumb1Only()) {
993 }
994 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
995 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
997
1007
1008 // MVE lowers 64 bit shifts to lsll and lsrl
1009 // assuming that ISD::SRL and SRA of i64 are already marked custom
1010 if (Subtarget->hasMVEIntegerOps())
1012
1013 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1014 if (Subtarget->isThumb1Only()) {
1018 }
1019
1020 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1022
1023 // ARM does not have ROTL.
1028 }
1030 // TODO: These two should be set to LibCall, but this currently breaks
1031 // the Linux kernel build. See #101786.
1034 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1037 }
1038
1039 // @llvm.readcyclecounter requires the Performance Monitors extension.
1040 // Default to the 0 expansion on unsupported platforms.
1041 // FIXME: Technically there are older ARM CPUs that have
1042 // implementation-specific ways of obtaining this information.
1043 if (Subtarget->hasPerfMon())
1045
1046 // Only ARMv6 has BSWAP.
1047 if (!Subtarget->hasV6Ops())
1049
1050 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1051 : Subtarget->hasDivideInARMMode();
1052 if (!hasDivide) {
1053 // These are expanded into libcalls if the cpu doesn't have HW divider.
1056 }
1057
1058 if (TT.isOSWindows() && !Subtarget->hasDivideInThumbMode()) {
1061
1064 }
1065
1068
1069 // Register based DivRem for AEABI (RTABI 4.2)
1070 if (TT.isTargetAEABI() || TT.isAndroid() || TT.isTargetGNUAEABI() ||
1071 TT.isTargetMuslAEABI() || TT.isOSFuchsia() || TT.isOSWindows()) {
1074 HasStandaloneRem = false;
1075
1080 } else {
1083 }
1084
1089
1090 setOperationAction(ISD::TRAP, MVT::Other, Legal);
1092
1093 // Use the default implementation.
1095 setOperationAction(ISD::VAARG, MVT::Other, Expand);
1097 setOperationAction(ISD::VAEND, MVT::Other, Expand);
1100
1101 if (TT.isOSWindows())
1103 else
1105
1106 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1107 // the default expansion.
1108 InsertFencesForAtomic = false;
1109 if (Subtarget->hasAnyDataBarrier() &&
1110 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1111 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1112 // to ldrex/strex loops already.
1114 if (!Subtarget->isThumb() || !Subtarget->isMClass())
1116
1117 // On v8, we have particularly efficient implementations of atomic fences
1118 // if they can be combined with nearby atomic loads and stores.
1119 if (!Subtarget->hasAcquireRelease() ||
1120 getTargetMachine().getOptLevel() == CodeGenOptLevel::None) {
1121 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1122 InsertFencesForAtomic = true;
1123 }
1124 } else {
1125 // If there's anything we can use as a barrier, go through custom lowering
1126 // for ATOMIC_FENCE.
1127 // If target has DMB in thumb, Fences can be inserted.
1128 if (Subtarget->hasDataBarrier())
1129 InsertFencesForAtomic = true;
1130
1132 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1133
1134 // Set them all for libcall, which will force libcalls.
1147 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1148 // Unordered/Monotonic case.
1149 if (!InsertFencesForAtomic) {
1152 }
1153 }
1154
1155 // Compute supported atomic widths.
1156 if (TT.isOSLinux() || (!Subtarget->isMClass() && Subtarget->hasV6Ops())) {
1157 // For targets where __sync_* routines are reliably available, we use them
1158 // if necessary.
1159 //
1160 // ARM Linux always supports 64-bit atomics through kernel-assisted atomic
1161 // routines (kernel 3.1 or later). FIXME: Not with compiler-rt?
1162 //
1163 // ARMv6 targets have native instructions in ARM mode. For Thumb mode,
1164 // such targets should provide __sync_* routines, which use the ARM mode
1165 // instructions. (ARMv6 doesn't have dmb, but it has an equivalent
1166 // encoding; see ARMISD::MEMBARRIER_MCR.)
1168 } else if ((Subtarget->isMClass() && Subtarget->hasV8MBaselineOps()) ||
1169 Subtarget->hasForced32BitAtomics()) {
1170 // Cortex-M (besides Cortex-M0) have 32-bit atomics.
1172 } else {
1173 // We can't assume anything about other targets; just use libatomic
1174 // routines.
1176 }
1177
1179
1181
1182 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1183 if (!Subtarget->hasV6Ops()) {
1186 }
1188
1189 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1190 !Subtarget->isThumb1Only()) {
1191 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1192 // iff target supports vfp2.
1202 }
1203
1204 // We want to custom lower some of our intrinsics.
1209
1219 if (Subtarget->hasFullFP16()) {
1223 }
1224
1226
1229 if (Subtarget->hasFullFP16())
1233 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
1234
1235 // We don't support sin/cos/fmod/copysign/pow
1244 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1245 !Subtarget->isThumb1Only()) {
1248 }
1251
1252 if (!Subtarget->hasVFP4Base()) {
1255 }
1256
1257 // Various VFP goodness
1258 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1259 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1260 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1265 }
1266
1267 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1268 if (!Subtarget->hasFP16()) {
1273 }
1274
1275 // Strict floating-point comparisons need custom lowering.
1282 }
1283
1284 // FP-ARMv8 implements a lot of rounding-like FP operations.
1285 if (Subtarget->hasFPARMv8Base()) {
1286 for (auto Op :
1293 setOperationAction(Op, MVT::f32, Legal);
1294
1295 if (Subtarget->hasFP64())
1296 setOperationAction(Op, MVT::f64, Legal);
1297 }
1298
1299 if (Subtarget->hasNEON()) {
1304 }
1305 }
1306
1307 // FP16 often need to be promoted to call lib functions
1308 // clang-format off
1309 if (Subtarget->hasFullFP16()) {
1313
1314 for (auto Op : {ISD::FREM, ISD::FPOW, ISD::FPOWI,
1328 setOperationAction(Op, MVT::f16, Promote);
1329 }
1330
1331 // Round-to-integer need custom lowering for fp16, as Promote doesn't work
1332 // because the result type is integer.
1334 setOperationAction(Op, MVT::f16, Custom);
1335
1341 setOperationAction(Op, MVT::f16, Legal);
1342 }
1343 // clang-format on
1344 }
1345
1346 if (Subtarget->hasNEON()) {
1347 // vmin and vmax aren't available in a scalar form, so we can use
1348 // a NEON instruction with an undef lane instead.
1357
1358 if (Subtarget->hasV8Ops()) {
1363 setOperationAction(Op, MVT::v2f32, Legal);
1364 setOperationAction(Op, MVT::v4f32, Legal);
1365 }
1366 }
1367
1368 if (Subtarget->hasFullFP16()) {
1373
1378
1383 setOperationAction(Op, MVT::v4f16, Legal);
1384 setOperationAction(Op, MVT::v8f16, Legal);
1385 }
1386 }
1387 }
1388
1389 // On MSVC, both 32-bit and 64-bit, ldexpf(f32) is not defined. MinGW has
1390 // it, but it's just a wrapper around ldexp.
1391 if (TT.isOSWindows()) {
1393 if (isOperationExpand(Op, MVT::f32))
1394 setOperationAction(Op, MVT::f32, Promote);
1395 }
1396
1397 // LegalizeDAG currently can't expand fp16 LDEXP/FREXP on targets where i16
1398 // isn't legal.
1400 if (isOperationExpand(Op, MVT::f16))
1401 setOperationAction(Op, MVT::f16, Promote);
1402
1403 // We have target-specific dag combine patterns for the following nodes:
1404 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1407
1408 if (Subtarget->hasMVEIntegerOps())
1410
1411 if (Subtarget->hasV6Ops())
1413 if (Subtarget->isThumb1Only())
1415 // Attempt to lower smin/smax to ssat/usat
1416 if ((!Subtarget->isThumb() && Subtarget->hasV6Ops()) ||
1417 Subtarget->isThumb2()) {
1419 }
1420
1422
1423 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1424 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1426 else
1428
1429 //// temporary - rewrite interface to use type
1432 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1434 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1436
1437 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1438 // are at least 4 bytes aligned.
1440
1441 // Prefer likely predicted branches to selects on out-of-order cores.
1442 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1443
1444 setPrefLoopAlignment(Align(1ULL << Subtarget->getPreferBranchLogAlignment()));
1446 Align(1ULL << Subtarget->getPreferBranchLogAlignment()));
1447
1448 setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4));
1449
1450 IsStrictFPEnabled = true;
1451}
1452
1454 return Subtarget->useSoftFloat();
1455}
1456
1458 return !Subtarget->isThumb1Only() && VT.getSizeInBits() <= 32;
1459}
1460
1461// FIXME: It might make sense to define the representative register class as the
1462// nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1463// a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1464// SPR's representative would be DPR_VFP2. This should work well if register
1465// pressure tracking were modified such that a register use would increment the
1466// pressure of the register class's representative and all of it's super
1467// classes' representatives transitively. We have not implemented this because
1468// of the difficulty prior to coalescing of modeling operand register classes
1469// due to the common occurrence of cross class copies and subregister insertions
1470// and extractions.
1471std::pair<const TargetRegisterClass *, uint8_t>
1473 MVT VT) const {
1474 const TargetRegisterClass *RRC = nullptr;
1475 uint8_t Cost = 1;
1476 switch (VT.SimpleTy) {
1477 default:
1479 // Use DPR as representative register class for all floating point
1480 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1481 // the cost is 1 for both f32 and f64.
1482 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1483 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1484 RRC = &ARM::DPRRegClass;
1485 // When NEON is used for SP, only half of the register file is available
1486 // because operations that define both SP and DP results will be constrained
1487 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1488 // coalescing by double-counting the SP regs. See the FIXME above.
1489 if (Subtarget->useNEONForSinglePrecisionFP())
1490 Cost = 2;
1491 break;
1492 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1493 case MVT::v4f32: case MVT::v2f64:
1494 RRC = &ARM::DPRRegClass;
1495 Cost = 2;
1496 break;
1497 case MVT::v4i64:
1498 RRC = &ARM::DPRRegClass;
1499 Cost = 4;
1500 break;
1501 case MVT::v8i64:
1502 RRC = &ARM::DPRRegClass;
1503 Cost = 8;
1504 break;
1505 }
1506 return std::make_pair(RRC, Cost);
1507}
1508
1510 EVT VT) const {
1511 if (!VT.isVector())
1512 return getPointerTy(DL);
1513
1514 // MVE has a predicate register.
1515 if (Subtarget->hasMVEIntegerOps())
1516 return EVT::getVectorVT(C, MVT::i1, VT.getVectorElementCount());
1517
1519}
1520
1521/// getRegClassFor - Return the register class that should be used for the
1522/// specified value type.
1523const TargetRegisterClass *
1524ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1525 (void)isDivergent;
1526 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1527 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1528 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1529 // MVE Q registers.
1530 if (Subtarget->hasNEON()) {
1531 if (VT == MVT::v4i64)
1532 return &ARM::QQPRRegClass;
1533 if (VT == MVT::v8i64)
1534 return &ARM::QQQQPRRegClass;
1535 }
1536 if (Subtarget->hasMVEIntegerOps()) {
1537 if (VT == MVT::v4i64)
1538 return &ARM::MQQPRRegClass;
1539 if (VT == MVT::v8i64)
1540 return &ARM::MQQQQPRRegClass;
1541 }
1543}
1544
1545// memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1546// source/dest is aligned and the copy size is large enough. We therefore want
1547// to align such objects passed to memory intrinsics.
1549 Align &PrefAlign) const {
1550 if (!isa<MemIntrinsic>(CI))
1551 return false;
1552 MinSize = 8;
1553 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1554 // cycle faster than 4-byte aligned LDM.
1555 PrefAlign =
1556 (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? Align(8) : Align(4));
1557 return true;
1558}
1559
1560// Create a fast isel object.
1562 FunctionLoweringInfo &funcInfo, const TargetLibraryInfo *libInfo,
1563 const LibcallLoweringInfo *libcallLowering) const {
1564 return ARM::createFastISel(funcInfo, libInfo, libcallLowering);
1565}
1566
1568 unsigned NumVals = N->getNumValues();
1569 if (!NumVals)
1570 return Sched::RegPressure;
1571
1572 for (unsigned i = 0; i != NumVals; ++i) {
1573 EVT VT = N->getValueType(i);
1574 if (VT == MVT::Glue || VT == MVT::Other)
1575 continue;
1576 if (VT.isFloatingPoint() || VT.isVector())
1577 return Sched::ILP;
1578 }
1579
1580 if (!N->isMachineOpcode())
1581 return Sched::RegPressure;
1582
1583 // Load are scheduled for latency even if there instruction itinerary
1584 // is not available.
1585 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1586 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1587
1588 if (MCID.getNumDefs() == 0)
1589 return Sched::RegPressure;
1590 if (!Itins->isEmpty() &&
1591 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2U)
1592 return Sched::ILP;
1593
1594 return Sched::RegPressure;
1595}
1596
1597//===----------------------------------------------------------------------===//
1598// Lowering Code
1599//===----------------------------------------------------------------------===//
1600
1601static bool isSRL16(const SDValue &Op) {
1602 if (Op.getOpcode() != ISD::SRL)
1603 return false;
1604 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1605 return Const->getZExtValue() == 16;
1606 return false;
1607}
1608
1609static bool isSRA16(const SDValue &Op) {
1610 if (Op.getOpcode() != ISD::SRA)
1611 return false;
1612 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1613 return Const->getZExtValue() == 16;
1614 return false;
1615}
1616
1617static bool isSHL16(const SDValue &Op) {
1618 if (Op.getOpcode() != ISD::SHL)
1619 return false;
1620 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1621 return Const->getZExtValue() == 16;
1622 return false;
1623}
1624
1625// Check for a signed 16-bit value. We special case SRA because it makes it
1626// more simple when also looking for SRAs that aren't sign extending a
1627// smaller value. Without the check, we'd need to take extra care with
1628// checking order for some operations.
1629static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1630 if (isSRA16(Op))
1631 return isSHL16(Op.getOperand(0));
1632 return DAG.ComputeNumSignBits(Op) == 17;
1633}
1634
1635/// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1637 switch (CC) {
1638 default: llvm_unreachable("Unknown condition code!");
1639 case ISD::SETNE: return ARMCC::NE;
1640 case ISD::SETEQ: return ARMCC::EQ;
1641 case ISD::SETGT: return ARMCC::GT;
1642 case ISD::SETGE: return ARMCC::GE;
1643 case ISD::SETLT: return ARMCC::LT;
1644 case ISD::SETLE: return ARMCC::LE;
1645 case ISD::SETUGT: return ARMCC::HI;
1646 case ISD::SETUGE: return ARMCC::HS;
1647 case ISD::SETULT: return ARMCC::LO;
1648 case ISD::SETULE: return ARMCC::LS;
1649 }
1650}
1651
1652/// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1654 ARMCC::CondCodes &CondCode2) {
1655 CondCode2 = ARMCC::AL;
1656 switch (CC) {
1657 default: llvm_unreachable("Unknown FP condition!");
1658 case ISD::SETEQ:
1659 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1660 case ISD::SETGT:
1661 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1662 case ISD::SETGE:
1663 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1664 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1665 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1666 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1667 case ISD::SETO: CondCode = ARMCC::VC; break;
1668 case ISD::SETUO: CondCode = ARMCC::VS; break;
1669 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1670 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1671 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1672 case ISD::SETLT:
1673 case ISD::SETULT: CondCode = ARMCC::LT; break;
1674 case ISD::SETLE:
1675 case ISD::SETULE: CondCode = ARMCC::LE; break;
1676 case ISD::SETNE:
1677 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1678 }
1679}
1680
1681//===----------------------------------------------------------------------===//
1682// Calling Convention Implementation
1683//===----------------------------------------------------------------------===//
1684
1685/// getEffectiveCallingConv - Get the effective calling convention, taking into
1686/// account presence of floating point hardware and calling convention
1687/// limitations, such as support for variadic functions.
1690 bool isVarArg) const {
1691 switch (CC) {
1692 default:
1693 // Unknown CCs are rejected when calling convention lowering is required.
1696 case CallingConv::GHC:
1698 return CC;
1704 case CallingConv::Swift:
1707 case CallingConv::C:
1708 case CallingConv::Tail:
1709 if (!Subtarget->isAAPCS_ABI())
1710 return CallingConv::ARM_APCS;
1711 else if (Subtarget->isTargetHardFloat() && !isVarArg)
1713 else
1715 case CallingConv::Fast:
1717 if (!Subtarget->isAAPCS_ABI()) {
1718 if (Subtarget->hasFPRegs() && !Subtarget->isThumb1Only() && !isVarArg)
1719 return CallingConv::Fast;
1720 return CallingConv::ARM_APCS;
1721 } else if (Subtarget->hasFPRegs() && !Subtarget->isThumb1Only() &&
1722 !isVarArg)
1724 else
1726 }
1727}
1728
1730 bool isVarArg) const {
1731 return CCAssignFnForNode(CC, false, isVarArg);
1732}
1733
1735 bool isVarArg) const {
1736 return CCAssignFnForNode(CC, true, isVarArg);
1737}
1738
1739/// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1740/// CallingConvention.
1741CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1742 bool Return,
1743 bool isVarArg) const {
1744 switch (getEffectiveCallingConv(CC, isVarArg)) {
1745 default:
1746 report_fatal_error("Unsupported calling convention");
1748 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1750 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1752 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1753 case CallingConv::Fast:
1754 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1755 case CallingConv::GHC:
1756 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1758 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1760 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1762 return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check);
1763 }
1764}
1765
1766SDValue ARMTargetLowering::MoveToHPR(const SDLoc &dl, SelectionDAG &DAG,
1767 MVT LocVT, MVT ValVT, SDValue Val) const {
1768 Val = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocVT.getSizeInBits()),
1769 Val);
1770 if (Subtarget->hasFullFP16()) {
1771 Val = DAG.getNode(ARMISD::VMOVhr, dl, ValVT, Val);
1772 } else {
1773 Val = DAG.getNode(ISD::TRUNCATE, dl,
1774 MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
1775 Val = DAG.getNode(ISD::BITCAST, dl, ValVT, Val);
1776 }
1777 return Val;
1778}
1779
1780SDValue ARMTargetLowering::MoveFromHPR(const SDLoc &dl, SelectionDAG &DAG,
1781 MVT LocVT, MVT ValVT,
1782 SDValue Val) const {
1783 if (Subtarget->hasFullFP16()) {
1784 Val = DAG.getNode(ARMISD::VMOVrh, dl,
1785 MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
1786 } else {
1787 Val = DAG.getNode(ISD::BITCAST, dl,
1788 MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
1789 Val = DAG.getNode(ISD::ZERO_EXTEND, dl,
1790 MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
1791 }
1792 return DAG.getNode(ISD::BITCAST, dl, LocVT, Val);
1793}
1794
1795/// LowerCallResult - Lower the result values of a call into the
1796/// appropriate copies out of appropriate physical registers.
1797SDValue ARMTargetLowering::LowerCallResult(
1798 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool isVarArg,
1799 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1800 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1801 SDValue ThisVal, bool isCmseNSCall) const {
1802 // Assign locations to each value returned by this call.
1804 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1805 *DAG.getContext());
1806 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1807
1808 // Copy all of the result registers out of their specified physreg.
1809 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1810 CCValAssign VA = RVLocs[i];
1811
1812 // Pass 'this' value directly from the argument to return value, to avoid
1813 // reg unit interference
1814 if (i == 0 && isThisReturn) {
1815 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1816 "unexpected return calling convention register assignment");
1817 InVals.push_back(ThisVal);
1818 continue;
1819 }
1820
1821 SDValue Val;
1822 if (VA.needsCustom() &&
1823 (VA.getLocVT() == MVT::f64 || VA.getLocVT() == MVT::v2f64)) {
1824 // Handle f64 or half of a v2f64.
1825 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1826 InGlue);
1827 Chain = Lo.getValue(1);
1828 InGlue = Lo.getValue(2);
1829 VA = RVLocs[++i]; // skip ahead to next loc
1830 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1831 InGlue);
1832 Chain = Hi.getValue(1);
1833 InGlue = Hi.getValue(2);
1834 if (!Subtarget->isLittle())
1835 std::swap (Lo, Hi);
1836 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1837
1838 if (VA.getLocVT() == MVT::v2f64) {
1839 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1840 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1841 DAG.getConstant(0, dl, MVT::i32));
1842
1843 VA = RVLocs[++i]; // skip ahead to next loc
1844 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InGlue);
1845 Chain = Lo.getValue(1);
1846 InGlue = Lo.getValue(2);
1847 VA = RVLocs[++i]; // skip ahead to next loc
1848 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InGlue);
1849 Chain = Hi.getValue(1);
1850 InGlue = Hi.getValue(2);
1851 if (!Subtarget->isLittle())
1852 std::swap (Lo, Hi);
1853 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1854 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1855 DAG.getConstant(1, dl, MVT::i32));
1856 }
1857 } else {
1858 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1859 InGlue);
1860 Chain = Val.getValue(1);
1861 InGlue = Val.getValue(2);
1862 }
1863
1864 switch (VA.getLocInfo()) {
1865 default: llvm_unreachable("Unknown loc info!");
1866 case CCValAssign::Full: break;
1867 case CCValAssign::BCvt:
1868 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1869 break;
1870 }
1871
1872 // f16 arguments have their size extended to 4 bytes and passed as if they
1873 // had been copied to the LSBs of a 32-bit register.
1874 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
1875 if (VA.needsCustom() &&
1876 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
1877 Val = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Val);
1878
1879 // On CMSE Non-secure Calls, call results (returned values) whose bitwidth
1880 // is less than 32 bits must be sign- or zero-extended after the call for
1881 // security reasons. Although the ABI mandates an extension done by the
1882 // callee, the latter cannot be trusted to follow the rules of the ABI.
1883 const ISD::InputArg &Arg = Ins[VA.getValNo()];
1884 if (isCmseNSCall && Arg.ArgVT.isScalarInteger() &&
1885 VA.getLocVT().isScalarInteger() && Arg.ArgVT.bitsLT(MVT::i32))
1886 Val = handleCMSEValue(Val, Arg, DAG, dl);
1887
1888 InVals.push_back(Val);
1889 }
1890
1891 return Chain;
1892}
1893
1894std::pair<SDValue, MachinePointerInfo> ARMTargetLowering::computeAddrForCallArg(
1895 const SDLoc &dl, SelectionDAG &DAG, const CCValAssign &VA, SDValue StackPtr,
1896 bool IsTailCall, int SPDiff) const {
1897 SDValue DstAddr;
1898 MachinePointerInfo DstInfo;
1899 int32_t Offset = VA.getLocMemOffset();
1901
1902 if (IsTailCall) {
1903 Offset += SPDiff;
1904 auto PtrVT = getPointerTy(DAG.getDataLayout());
1905 int Size = VA.getLocVT().getFixedSizeInBits() / 8;
1906 int FI = MF.getFrameInfo().CreateFixedObject(Size, Offset, true);
1907 DstAddr = DAG.getFrameIndex(FI, PtrVT);
1908 DstInfo =
1910 } else {
1911 SDValue PtrOff = DAG.getIntPtrConstant(Offset, dl);
1912 DstAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1913 StackPtr, PtrOff);
1914 DstInfo =
1916 }
1917
1918 return std::make_pair(DstAddr, DstInfo);
1919}
1920
1921// Returns the type of copying which is required to set up a byval argument to
1922// a tail-called function. This isn't needed for non-tail calls, because they
1923// always need the equivalent of CopyOnce, but tail-calls sometimes need two to
1924// avoid clobbering another argument (CopyViaTemp), and sometimes can be
1925// optimised to zero copies when forwarding an argument from the caller's
1926// caller (NoCopy).
1927ARMTargetLowering::ByValCopyKind ARMTargetLowering::ByValNeedsCopyForTailCall(
1928 SelectionDAG &DAG, SDValue Src, SDValue Dst, ISD::ArgFlagsTy Flags) const {
1929 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1930 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
1931
1932 // Globals are always safe to copy from.
1934 return CopyOnce;
1935
1936 // Can only analyse frame index nodes, conservatively assume we need a
1937 // temporary.
1938 auto *SrcFrameIdxNode = dyn_cast<FrameIndexSDNode>(Src);
1939 auto *DstFrameIdxNode = dyn_cast<FrameIndexSDNode>(Dst);
1940 if (!SrcFrameIdxNode || !DstFrameIdxNode)
1941 return CopyViaTemp;
1942
1943 int SrcFI = SrcFrameIdxNode->getIndex();
1944 int DstFI = DstFrameIdxNode->getIndex();
1945 assert(MFI.isFixedObjectIndex(DstFI) &&
1946 "byval passed in non-fixed stack slot");
1947
1948 int64_t SrcOffset = MFI.getObjectOffset(SrcFI);
1949 int64_t DstOffset = MFI.getObjectOffset(DstFI);
1950
1951 // If the source is in the local frame, then the copy to the argument memory
1952 // is always valid.
1953 bool FixedSrc = MFI.isFixedObjectIndex(SrcFI);
1954 if (!FixedSrc ||
1955 (FixedSrc && SrcOffset < -(int64_t)AFI->getArgRegsSaveSize()))
1956 return CopyOnce;
1957
1958 // In the case of byval arguments split between registers and the stack,
1959 // computeAddrForCallArg returns a FrameIndex which corresponds only to the
1960 // stack portion, but the Src SDValue will refer to the full value, including
1961 // the local stack memory that the register portion gets stored into. We only
1962 // need to compare them for equality, so normalise on the full value version.
1963 uint64_t RegSize = Flags.getByValSize() - MFI.getObjectSize(DstFI);
1964 DstOffset -= RegSize;
1965
1966 // If the value is already in the correct location, then no copying is
1967 // needed. If not, then we need to copy via a temporary.
1968 if (SrcOffset == DstOffset)
1969 return NoCopy;
1970 else
1971 return CopyViaTemp;
1972}
1973
1974void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1975 SDValue Chain, SDValue &Arg,
1976 RegsToPassVector &RegsToPass,
1977 CCValAssign &VA, CCValAssign &NextVA,
1978 SDValue &StackPtr,
1979 SmallVectorImpl<SDValue> &MemOpChains,
1980 bool IsTailCall,
1981 int SPDiff) const {
1982 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1983 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1984 unsigned id = Subtarget->isLittle() ? 0 : 1;
1985 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1986
1987 if (NextVA.isRegLoc())
1988 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1989 else {
1990 assert(NextVA.isMemLoc());
1991 if (!StackPtr.getNode())
1992 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1994
1995 SDValue DstAddr;
1996 MachinePointerInfo DstInfo;
1997 std::tie(DstAddr, DstInfo) =
1998 computeAddrForCallArg(dl, DAG, NextVA, StackPtr, IsTailCall, SPDiff);
1999 MemOpChains.push_back(
2000 DAG.getStore(Chain, dl, fmrrd.getValue(1 - id), DstAddr, DstInfo));
2001 }
2002}
2003
2004static bool canGuaranteeTCO(CallingConv::ID CC, bool GuaranteeTailCalls) {
2005 return (CC == CallingConv::Fast && GuaranteeTailCalls) ||
2007}
2008
2009/// LowerCall - Lowering a call into a callseq_start <-
2010/// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2011/// nodes.
2012SDValue
2013ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2014 SmallVectorImpl<SDValue> &InVals) const {
2015 SelectionDAG &DAG = CLI.DAG;
2016 SDLoc &dl = CLI.DL;
2017 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2018 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2019 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2020 SDValue Chain = CLI.Chain;
2021 SDValue Callee = CLI.Callee;
2022 bool &isTailCall = CLI.IsTailCall;
2023 CallingConv::ID CallConv = CLI.CallConv;
2024 bool doesNotRet = CLI.DoesNotReturn;
2025 bool isVarArg = CLI.IsVarArg;
2026 const CallBase *CB = CLI.CB;
2027
2029 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2030 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2031 MachineFunction::CallSiteInfo CSInfo;
2032 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2033 bool isThisReturn = false;
2034 bool isCmseNSCall = false;
2035 bool isSibCall = false;
2036 bool PreferIndirect = false;
2037 bool GuardWithBTI = false;
2038
2039 // Analyze operands of the call, assigning locations to each operand.
2041 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2042 *DAG.getContext());
2043 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2044
2045 // Lower 'returns_twice' calls to a pseudo-instruction.
2046 if (CLI.CB && CLI.CB->getAttributes().hasFnAttr(Attribute::ReturnsTwice) &&
2047 !Subtarget->noBTIAtReturnTwice())
2048 GuardWithBTI = AFI->branchTargetEnforcement();
2049
2050 // Set type id for call site info.
2051 setTypeIdForCallsiteInfo(CB, MF, CSInfo);
2052
2053 // Determine whether this is a non-secure function call.
2054 if (CLI.CB && CLI.CB->getAttributes().hasFnAttr("cmse_nonsecure_call"))
2055 isCmseNSCall = true;
2056
2057 // Disable tail calls if they're not supported.
2058 if (!Subtarget->supportsTailCall())
2059 isTailCall = false;
2060
2061 // For both the non-secure calls and the returns from a CMSE entry function,
2062 // the function needs to do some extra work after the call, or before the
2063 // return, respectively, thus it cannot end with a tail call
2064 if (isCmseNSCall || AFI->isCmseNSEntryFunction())
2065 isTailCall = false;
2066
2067 if (isa<GlobalAddressSDNode>(Callee)) {
2068 // If we're optimizing for minimum size and the function is called three or
2069 // more times in this block, we can improve codesize by calling indirectly
2070 // as BLXr has a 16-bit encoding.
2071 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2072 if (CLI.CB) {
2073 auto *BB = CLI.CB->getParent();
2074 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2075 count_if(GV->users(), [&BB](const User *U) {
2076 return isa<Instruction>(U) &&
2077 cast<Instruction>(U)->getParent() == BB;
2078 }) > 2;
2079 }
2080 }
2081 if (isTailCall) {
2082 // Check if it's really possible to do a tail call.
2083 isTailCall =
2084 IsEligibleForTailCallOptimization(CLI, CCInfo, ArgLocs, PreferIndirect);
2085
2086 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt &&
2087 CallConv != CallingConv::Tail && CallConv != CallingConv::SwiftTail)
2088 isSibCall = true;
2089
2090 // We don't support GuaranteedTailCallOpt for ARM, only automatically
2091 // detected sibcalls.
2092 if (isTailCall)
2093 ++NumTailCalls;
2094 }
2095
2096 if (!isTailCall && CLI.CB && CLI.CB->isMustTailCall())
2097 report_fatal_error("failed to perform tail call elimination on a call "
2098 "site marked musttail");
2099
2100 // Get a count of how many bytes are to be pushed on the stack.
2101 unsigned NumBytes = CCInfo.getStackSize();
2102
2103 // SPDiff is the byte offset of the call's argument area from the callee's.
2104 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2105 // by this amount for a tail call. In a sibling call it must be 0 because the
2106 // caller will deallocate the entire stack and the callee still expects its
2107 // arguments to begin at SP+0. Completely unused for non-tail calls.
2108 int SPDiff = 0;
2109
2110 if (isTailCall && !isSibCall) {
2111 auto FuncInfo = MF.getInfo<ARMFunctionInfo>();
2112 unsigned NumReusableBytes = FuncInfo->getArgumentStackSize();
2113
2114 // Since callee will pop argument stack as a tail call, we must keep the
2115 // popped size 16-byte aligned.
2116 MaybeAlign StackAlign = DAG.getDataLayout().getStackAlignment();
2117 assert(StackAlign && "data layout string is missing stack alignment");
2118 NumBytes = alignTo(NumBytes, *StackAlign);
2119
2120 // SPDiff will be negative if this tail call requires more space than we
2121 // would automatically have in our incoming argument space. Positive if we
2122 // can actually shrink the stack.
2123 SPDiff = NumReusableBytes - NumBytes;
2124
2125 // If this call requires more stack than we have available from
2126 // LowerFormalArguments, tell FrameLowering to reserve space for it.
2127 if (SPDiff < 0 && AFI->getArgRegsSaveSize() < (unsigned)-SPDiff)
2128 AFI->setArgRegsSaveSize(-SPDiff);
2129 }
2130
2131 if (isSibCall) {
2132 // For sibling tail calls, memory operands are available in our caller's stack.
2133 NumBytes = 0;
2134 } else {
2135 // Adjust the stack pointer for the new arguments...
2136 // These operations are automatically eliminated by the prolog/epilog pass
2137 Chain = DAG.getCALLSEQ_START(Chain, isTailCall ? 0 : NumBytes, 0, dl);
2138 }
2139
2141 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2142
2143 RegsToPassVector RegsToPass;
2144 SmallVector<SDValue, 8> MemOpChains;
2145
2146 // If we are doing a tail-call, any byval arguments will be written to stack
2147 // space which was used for incoming arguments. If any the values being used
2148 // are incoming byval arguments to this function, then they might be
2149 // overwritten by the stores of the outgoing arguments. To avoid this, we
2150 // need to make a temporary copy of them in local stack space, then copy back
2151 // to the argument area.
2152 DenseMap<unsigned, SDValue> ByValTemporaries;
2153 SDValue ByValTempChain;
2154 if (isTailCall) {
2155 SmallVector<SDValue, 8> ByValCopyChains;
2156 for (const CCValAssign &VA : ArgLocs) {
2157 unsigned ArgIdx = VA.getValNo();
2158 SDValue Src = OutVals[ArgIdx];
2159 ISD::ArgFlagsTy Flags = Outs[ArgIdx].Flags;
2160
2161 if (!Flags.isByVal())
2162 continue;
2163
2164 SDValue Dst;
2165 MachinePointerInfo DstInfo;
2166 std::tie(Dst, DstInfo) =
2167 computeAddrForCallArg(dl, DAG, VA, SDValue(), true, SPDiff);
2168 ByValCopyKind Copy = ByValNeedsCopyForTailCall(DAG, Src, Dst, Flags);
2169
2170 if (Copy == NoCopy) {
2171 // If the argument is already at the correct offset on the stack
2172 // (because we are forwarding a byval argument from our caller), we
2173 // don't need any copying.
2174 continue;
2175 } else if (Copy == CopyOnce) {
2176 // If the argument is in our local stack frame, no other argument
2177 // preparation can clobber it, so we can copy it to the final location
2178 // later.
2179 ByValTemporaries[ArgIdx] = Src;
2180 } else {
2181 assert(Copy == CopyViaTemp && "unexpected enum value");
2182 // If we might be copying this argument from the outgoing argument
2183 // stack area, we need to copy via a temporary in the local stack
2184 // frame.
2185 int TempFrameIdx = MFI.CreateStackObject(
2186 Flags.getByValSize(), Flags.getNonZeroByValAlign(), false);
2187 SDValue Temp =
2188 DAG.getFrameIndex(TempFrameIdx, getPointerTy(DAG.getDataLayout()));
2189
2190 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2191 SDValue AlignNode =
2192 DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32);
2193
2194 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2195 SDValue Ops[] = {Chain, Temp, Src, SizeNode, AlignNode};
2196 ByValCopyChains.push_back(
2197 DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, Ops));
2198 ByValTemporaries[ArgIdx] = Temp;
2199 }
2200 }
2201 if (!ByValCopyChains.empty())
2202 ByValTempChain =
2203 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, ByValCopyChains);
2204 }
2205
2206 // During a tail call, stores to the argument area must happen after all of
2207 // the function's incoming arguments have been loaded because they may alias.
2208 // This is done by folding in a TokenFactor from LowerFormalArguments, but
2209 // there's no point in doing so repeatedly so this tracks whether that's
2210 // happened yet.
2211 bool AfterFormalArgLoads = false;
2212
2213 // Walk the register/memloc assignments, inserting copies/loads. In the case
2214 // of tail call optimization, arguments are handled later.
2215 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2216 i != e;
2217 ++i, ++realArgIdx) {
2218 CCValAssign &VA = ArgLocs[i];
2219 SDValue Arg = OutVals[realArgIdx];
2220 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2221 bool isByVal = Flags.isByVal();
2222
2223 // Promote the value if needed.
2224 switch (VA.getLocInfo()) {
2225 default: llvm_unreachable("Unknown loc info!");
2226 case CCValAssign::Full: break;
2227 case CCValAssign::SExt:
2228 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2229 break;
2230 case CCValAssign::ZExt:
2231 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2232 break;
2233 case CCValAssign::AExt:
2234 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2235 break;
2236 case CCValAssign::BCvt:
2237 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2238 break;
2239 }
2240
2241 if (isTailCall && VA.isMemLoc() && !AfterFormalArgLoads) {
2242 Chain = DAG.getStackArgumentTokenFactor(Chain);
2243 if (ByValTempChain) {
2244 // In case of large byval copies, re-using the stackframe for tail-calls
2245 // can lead to overwriting incoming arguments on the stack. Force
2246 // loading these stack arguments before the copy to avoid that.
2247 SmallVector<SDValue, 8> IncomingLoad;
2248 for (unsigned I = 0; I < OutVals.size(); ++I) {
2249 if (Outs[I].Flags.isByVal())
2250 continue;
2251
2252 SDValue OutVal = OutVals[I];
2253 LoadSDNode *OutLN = dyn_cast_or_null<LoadSDNode>(OutVal);
2254 if (!OutLN)
2255 continue;
2256
2257 FrameIndexSDNode *FIN =
2259 if (!FIN)
2260 continue;
2261
2262 if (!MFI.isFixedObjectIndex(FIN->getIndex()))
2263 continue;
2264
2265 for (const CCValAssign &VA : ArgLocs) {
2266 if (VA.isMemLoc())
2267 IncomingLoad.push_back(OutVal.getValue(1));
2268 }
2269 }
2270
2271 // Update the chain to force loads for potentially clobbered argument
2272 // loads to happen before the byval copy.
2273 if (!IncomingLoad.empty()) {
2274 IncomingLoad.push_back(Chain);
2275 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, IncomingLoad);
2276 }
2277
2278 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chain,
2279 ByValTempChain);
2280 }
2281 AfterFormalArgLoads = true;
2282 }
2283
2284 // f16 arguments have their size extended to 4 bytes and passed as if they
2285 // had been copied to the LSBs of a 32-bit register.
2286 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
2287 if (VA.needsCustom() &&
2288 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) {
2289 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
2290 } else {
2291 // f16 arguments could have been extended prior to argument lowering.
2292 // Mask them arguments if this is a CMSE nonsecure call.
2293 auto ArgVT = Outs[realArgIdx].ArgVT;
2294 if (isCmseNSCall && (ArgVT == MVT::f16)) {
2295 auto LocBits = VA.getLocVT().getSizeInBits();
2296 auto MaskValue = APInt::getLowBitsSet(LocBits, ArgVT.getSizeInBits());
2297 SDValue Mask =
2298 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
2299 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
2300 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
2301 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2302 }
2303 }
2304
2305 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2306 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
2307 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2308 DAG.getConstant(0, dl, MVT::i32));
2309 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2310 DAG.getConstant(1, dl, MVT::i32));
2311
2312 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, VA, ArgLocs[++i],
2313 StackPtr, MemOpChains, isTailCall, SPDiff);
2314
2315 VA = ArgLocs[++i]; // skip ahead to next loc
2316 if (VA.isRegLoc()) {
2317 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, VA, ArgLocs[++i],
2318 StackPtr, MemOpChains, isTailCall, SPDiff);
2319 } else {
2320 assert(VA.isMemLoc());
2321 SDValue DstAddr;
2322 MachinePointerInfo DstInfo;
2323 std::tie(DstAddr, DstInfo) =
2324 computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2325 MemOpChains.push_back(DAG.getStore(Chain, dl, Op1, DstAddr, DstInfo));
2326 }
2327 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
2328 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2329 StackPtr, MemOpChains, isTailCall, SPDiff);
2330 } else if (VA.isRegLoc()) {
2331 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2332 Outs[0].VT == MVT::i32) {
2333 assert(VA.getLocVT() == MVT::i32 &&
2334 "unexpected calling convention register assignment");
2335 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2336 "unexpected use of 'returned'");
2337 isThisReturn = true;
2338 }
2339 const TargetOptions &Options = DAG.getTarget().Options;
2340 if (Options.EmitCallSiteInfo)
2341 CSInfo.ArgRegPairs.emplace_back(VA.getLocReg(), i);
2342 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2343 } else if (isByVal) {
2344 assert(VA.isMemLoc());
2345 unsigned offset = 0;
2346
2347 // True if this byval aggregate will be split between registers
2348 // and memory.
2349 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2350 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2351
2352 SDValue ByValSrc;
2353 bool NeedsStackCopy;
2354 if (auto It = ByValTemporaries.find(realArgIdx);
2355 It != ByValTemporaries.end()) {
2356 ByValSrc = It->second;
2357 NeedsStackCopy = true;
2358 } else {
2359 ByValSrc = Arg;
2360 NeedsStackCopy = !isTailCall;
2361 }
2362
2363 // If part of the argument is in registers, load them.
2364 if (CurByValIdx < ByValArgsCount) {
2365 unsigned RegBegin, RegEnd;
2366 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2367
2368 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2369 unsigned int i, j;
2370 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2371 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2372 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, ByValSrc, Const);
2373 SDValue Load =
2374 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(),
2375 DAG.InferPtrAlign(AddArg));
2376 MemOpChains.push_back(Load.getValue(1));
2377 RegsToPass.push_back(std::make_pair(j, Load));
2378 }
2379
2380 // If parameter size outsides register area, "offset" value
2381 // helps us to calculate stack slot for remained part properly.
2382 offset = RegEnd - RegBegin;
2383
2384 CCInfo.nextInRegsParam();
2385 }
2386
2387 // If the memory part of the argument isn't already in the correct place
2388 // (which can happen with tail calls), copy it into the argument area.
2389 if (NeedsStackCopy && Flags.getByValSize() > 4 * offset) {
2390 auto PtrVT = getPointerTy(DAG.getDataLayout());
2391 SDValue Dst;
2392 MachinePointerInfo DstInfo;
2393 std::tie(Dst, DstInfo) =
2394 computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2395 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2396 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, ByValSrc, SrcOffset);
2397 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2398 MVT::i32);
2399 SDValue AlignNode =
2400 DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32);
2401
2402 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2403 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2404 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2405 Ops));
2406 }
2407 } else {
2408 assert(VA.isMemLoc());
2409 SDValue DstAddr;
2410 MachinePointerInfo DstInfo;
2411 std::tie(DstAddr, DstInfo) =
2412 computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2413
2414 SDValue Store = DAG.getStore(Chain, dl, Arg, DstAddr, DstInfo);
2415 MemOpChains.push_back(Store);
2416 }
2417 }
2418
2419 if (!MemOpChains.empty())
2420 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2421
2422 // Build a sequence of copy-to-reg nodes chained together with token chain
2423 // and flag operands which copy the outgoing args into the appropriate regs.
2424 SDValue InGlue;
2425 for (const auto &[Reg, N] : RegsToPass) {
2426 Chain = DAG.getCopyToReg(Chain, dl, Reg, N, InGlue);
2427 InGlue = Chain.getValue(1);
2428 }
2429
2430 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2431 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2432 // node so that legalize doesn't hack it.
2433 bool isDirect = false;
2434
2435 const TargetMachine &TM = getTargetMachine();
2436 const Triple &TT = TM.getTargetTriple();
2437 const GlobalValue *GVal = nullptr;
2438 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2439 GVal = G->getGlobal();
2440 bool isStub = !TM.shouldAssumeDSOLocal(GVal) && TT.isOSBinFormatMachO();
2441
2442 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2443 bool isLocalARMFunc = false;
2444 auto PtrVt = getPointerTy(DAG.getDataLayout());
2445
2446 if (Subtarget->genLongCalls()) {
2447 bool isPIC = isPositionIndependent() && !TT.isOSWindows();
2448 if (isPIC && Subtarget->genExecuteOnly())
2449 reportFatalUsageError("long-calls with execute-only and "
2450 "position-independent code is not supported");
2451 if (Subtarget->isROPI())
2452 reportFatalUsageError("long-calls with ROPI is not currently supported");
2453
2454 // Handle a global address or an external symbol. If it's not one of
2455 // those, the target's already in a register, so we don't need to do
2456 // anything extra.
2457 if (isa<GlobalAddressSDNode>(Callee)) {
2458 if (Subtarget->genExecuteOnly()) {
2459 // Execute-only forbids constant pools in .text, so use movw/movt.
2460 // fPIC is not supported with execute-only.
2461 if (Subtarget->useMovt())
2462 ++NumMovwMovt;
2463 Callee = DAG.getNode(ARMISD::Wrapper, dl, PtrVt,
2464 DAG.getTargetGlobalAddress(GVal, dl, PtrVt));
2465 } else if (isPIC) {
2466 // PIC without execute-only: use GOT-based addressing.
2467 // DSO-local symbols use a plain PC-relative WrapperPIC;
2468 // non-DSO-local symbols additionally load the address from the GOT.
2470 GVal, dl, PtrVt, 0, GVal->isDSOLocal() ? 0 : ARMII::MO_GOT);
2471 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVt, G);
2472 if (!GVal->isDSOLocal())
2473 Callee =
2474 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
2476 } else {
2477 // Neither execute-only nor PIC: load the address from a constant pool.
2478 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2479 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2480 GVal, ARMPCLabelIndex, ARMCP::CPValue, 0);
2481
2482 // Get the address of the callee into a register
2483 SDValue Addr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2484 Addr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Addr);
2485 Callee = DAG.getLoad(
2486 PtrVt, dl, DAG.getEntryNode(), Addr,
2488 }
2489 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2490 const char *Sym = S->getSymbol();
2491
2492 if (Subtarget->genExecuteOnly()) {
2493 // Execute-only forbids constant pools in .text, so use movw/movt.
2494 // fPIC is not supported with execute-only.
2495 if (Subtarget->useMovt())
2496 ++NumMovwMovt;
2497 Callee = DAG.getNode(ARMISD::Wrapper, dl, PtrVt,
2498 DAG.getTargetExternalSymbol(Sym, PtrVt, 0));
2499 } else if (isPIC) {
2500 // PIC without execute-only: load the symbol's address from the GOT via
2501 // a GOT_PREL constant pool entry consumed by a PICLDR.
2502 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2503 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2504 ARMConstantPoolValue *CPV = ARMConstantPoolSymbol::Create(
2505 *DAG.getContext(), Sym, ARMPCLabelIndex, PCAdj, ARMCP::GOT_PREL,
2506 /*AddCurrentAddress=*/true);
2507 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2508 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2509 SDValue GOTOffset = DAG.getLoad(
2510 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2512 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2513 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, GOTOffset, PICLabel);
2514 Callee =
2515 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
2517 } else {
2518 // Neither execute-only nor PIC: load the address from a constant pool.
2519 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2520 ARMConstantPoolValue *CPV = ARMConstantPoolSymbol::Create(
2521 *DAG.getContext(), Sym, ARMPCLabelIndex, 0);
2522
2523 // Get the address of the callee into a register
2524 SDValue Addr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2525 Addr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Addr);
2526 Callee = DAG.getLoad(
2527 PtrVt, dl, DAG.getEntryNode(), Addr,
2529 }
2530 }
2531 } else if (isa<GlobalAddressSDNode>(Callee)) {
2532 if (!PreferIndirect) {
2533 isDirect = true;
2534 bool isDef = GVal->isStrongDefinitionForLinker();
2535
2536 // ARM call to a local ARM function is predicable.
2537 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2538 // tBX takes a register source operand.
2539 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2540 assert(TT.isOSBinFormatMachO() && "WrapperPIC use on non-MachO?");
2541 Callee = DAG.getNode(
2542 ARMISD::WrapperPIC, dl, PtrVt,
2543 DAG.getTargetGlobalAddress(GVal, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2544 Callee = DAG.getLoad(
2545 PtrVt, dl, DAG.getEntryNode(), Callee,
2549 } else if (Subtarget->isTargetCOFF()) {
2550 assert(Subtarget->isTargetWindows() &&
2551 "Windows is the only supported COFF target");
2552 unsigned TargetFlags = ARMII::MO_NO_FLAG;
2553 if (GVal->hasDLLImportStorageClass())
2554 TargetFlags = ARMII::MO_DLLIMPORT;
2555 else if (!TM.shouldAssumeDSOLocal(GVal))
2556 TargetFlags = ARMII::MO_COFFSTUB;
2557 Callee = DAG.getTargetGlobalAddress(GVal, dl, PtrVt, /*offset=*/0,
2558 TargetFlags);
2559 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
2560 Callee =
2561 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2562 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2564 } else {
2565 Callee = DAG.getTargetGlobalAddress(GVal, dl, PtrVt, 0, 0);
2566 }
2567 }
2568 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2569 isDirect = true;
2570 // tBX takes a register source operand.
2571 const char *Sym = S->getSymbol();
2572 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2573 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2574 ARMConstantPoolValue *CPV =
2576 ARMPCLabelIndex, 4);
2577 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2578 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2579 Callee = DAG.getLoad(
2580 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2582 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2583 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2584 } else {
2585 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2586 }
2587 }
2588
2589 if (isCmseNSCall) {
2590 assert(!isARMFunc && !isDirect &&
2591 "Cannot handle call to ARM function or direct call");
2592 if (NumBytes > 0) {
2593 DAG.getContext()->diagnose(
2594 DiagnosticInfoUnsupported(DAG.getMachineFunction().getFunction(),
2595 "call to non-secure function would require "
2596 "passing arguments on stack",
2597 dl.getDebugLoc()));
2598 }
2599 if (isStructRet) {
2600 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
2602 "call to non-secure function would return value through pointer",
2603 dl.getDebugLoc()));
2604 }
2605 }
2606
2607 // FIXME: handle tail calls differently.
2608 unsigned CallOpc;
2609 if (Subtarget->isThumb()) {
2610 if (GuardWithBTI)
2611 CallOpc = ARMISD::t2CALL_BTI;
2612 else if (isCmseNSCall)
2613 CallOpc = ARMISD::tSECALL;
2614 else if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2615 CallOpc = ARMISD::CALL_NOLINK;
2616 else
2617 CallOpc = ARMISD::CALL;
2618 } else {
2619 if (!isDirect && !Subtarget->hasV5TOps())
2620 CallOpc = ARMISD::CALL_NOLINK;
2621 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2622 // Emit regular call when code size is the priority
2623 !Subtarget->hasMinSize())
2624 // "mov lr, pc; b _foo" to avoid confusing the RSP
2625 CallOpc = ARMISD::CALL_NOLINK;
2626 else
2627 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2628 }
2629
2630 // We don't usually want to end the call-sequence here because we would tidy
2631 // the frame up *after* the call, however in the ABI-changing tail-call case
2632 // we've carefully laid out the parameters so that when sp is reset they'll be
2633 // in the correct location.
2634 if (isTailCall && !isSibCall) {
2635 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, dl);
2636 InGlue = Chain.getValue(1);
2637 }
2638
2639 std::vector<SDValue> Ops;
2640 Ops.push_back(Chain);
2641 Ops.push_back(Callee);
2642
2643 if (isTailCall) {
2644 Ops.push_back(DAG.getSignedTargetConstant(SPDiff, dl, MVT::i32));
2645 }
2646
2647 // Add argument registers to the end of the list so that they are known live
2648 // into the call.
2649 for (const auto &[Reg, N] : RegsToPass)
2650 Ops.push_back(DAG.getRegister(Reg, N.getValueType()));
2651
2652 // Add a register mask operand representing the call-preserved registers.
2653 const uint32_t *Mask;
2654 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2655 if (isThisReturn) {
2656 // For 'this' returns, use the R0-preserving mask if applicable
2657 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2658 if (!Mask) {
2659 // Set isThisReturn to false if the calling convention is not one that
2660 // allows 'returned' to be modeled in this way, so LowerCallResult does
2661 // not try to pass 'this' straight through
2662 isThisReturn = false;
2663 Mask = ARI->getCallPreservedMask(MF, CallConv);
2664 }
2665 } else
2666 Mask = ARI->getCallPreservedMask(MF, CallConv);
2667
2668 assert(Mask && "Missing call preserved mask for calling convention");
2669 Ops.push_back(DAG.getRegisterMask(Mask));
2670
2671 if (InGlue.getNode())
2672 Ops.push_back(InGlue);
2673
2674 if (isTailCall) {
2676 SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, MVT::Other, Ops);
2677 if (CLI.CFIType)
2678 Ret.getNode()->setCFIType(CLI.CFIType->getZExtValue());
2679 DAG.addNoMergeSiteInfo(Ret.getNode(), CLI.NoMerge);
2680 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
2681 return Ret;
2682 }
2683
2684 // Returns a chain and a flag for retval copy to use.
2685 Chain = DAG.getNode(CallOpc, dl, {MVT::Other, MVT::Glue}, Ops);
2686 if (CLI.CFIType)
2687 Chain.getNode()->setCFIType(CLI.CFIType->getZExtValue());
2688 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
2689 InGlue = Chain.getValue(1);
2690 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
2691
2692 // If we're guaranteeing tail-calls will be honoured, the callee must
2693 // pop its own argument stack on return. But this call is *not* a tail call so
2694 // we need to undo that after it returns to restore the status-quo.
2695 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
2696 uint64_t CalleePopBytes =
2697 canGuaranteeTCO(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : -1U;
2698
2699 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, CalleePopBytes, InGlue, dl);
2700 if (!Ins.empty())
2701 InGlue = Chain.getValue(1);
2702
2703 // Handle result values, copying them out of physregs into vregs that we
2704 // return.
2705 return LowerCallResult(Chain, InGlue, CallConv, isVarArg, Ins, dl, DAG,
2706 InVals, isThisReturn,
2707 isThisReturn ? OutVals[0] : SDValue(), isCmseNSCall);
2708}
2709
2710/// HandleByVal - Every parameter *after* a byval parameter is passed
2711/// on the stack. Remember the next parameter register to allocate,
2712/// and then confiscate the rest of the parameter registers to insure
2713/// this.
2714void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2715 Align Alignment) const {
2716 // Byval (as with any stack) slots are always at least 4 byte aligned.
2717 Alignment = std::max(Alignment, Align(4));
2718
2719 MCRegister Reg = State->AllocateReg(GPRArgRegs);
2720 if (!Reg)
2721 return;
2722
2723 unsigned AlignInRegs = Alignment.value() / 4;
2724 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2725 for (unsigned i = 0; i < Waste; ++i)
2726 Reg = State->AllocateReg(GPRArgRegs);
2727
2728 if (!Reg)
2729 return;
2730
2731 unsigned Excess = 4 * (ARM::R4 - Reg);
2732
2733 // Special case when NSAA != SP and parameter size greater than size of
2734 // all remained GPR regs. In that case we can't split parameter, we must
2735 // send it to stack. We also must set NCRN to R4, so waste all
2736 // remained registers.
2737 const unsigned NSAAOffset = State->getStackSize();
2738 if (NSAAOffset != 0 && Size > Excess) {
2739 while (State->AllocateReg(GPRArgRegs))
2740 ;
2741 return;
2742 }
2743
2744 // First register for byval parameter is the first register that wasn't
2745 // allocated before this method call, so it would be "reg".
2746 // If parameter is small enough to be saved in range [reg, r4), then
2747 // the end (first after last) register would be reg + param-size-in-regs,
2748 // else parameter would be splitted between registers and stack,
2749 // end register would be r4 in this case.
2750 unsigned ByValRegBegin = Reg;
2751 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2752 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2753 // Note, first register is allocated in the beginning of function already,
2754 // allocate remained amount of registers we need.
2755 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2756 State->AllocateReg(GPRArgRegs);
2757 // A byval parameter that is split between registers and memory needs its
2758 // size truncated here.
2759 // In the case where the entire structure fits in registers, we set the
2760 // size in memory to zero.
2761 Size = std::max<int>(Size - Excess, 0);
2762}
2763
2764/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2765/// for tail call optimization. Targets which want to do tail call
2766/// optimization should implement this function. Note that this function also
2767/// processes musttail calls, so when this function returns false on a valid
2768/// musttail call, a fatal backend error occurs.
2769bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2771 SmallVectorImpl<CCValAssign> &ArgLocs, const bool isIndirect) const {
2772 CallingConv::ID CalleeCC = CLI.CallConv;
2773 SDValue Callee = CLI.Callee;
2774 bool isVarArg = CLI.IsVarArg;
2775 const SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2776 const SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2777 const SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2778 const SelectionDAG &DAG = CLI.DAG;
2780 const Function &CallerF = MF.getFunction();
2781 CallingConv::ID CallerCC = CallerF.getCallingConv();
2782
2783 assert(Subtarget->supportsTailCall());
2784
2785 // Indirect tail-calls require a register to hold the target address. That
2786 // register must be:
2787 // * Allocatable (i.e. r0-r7 if the target is Thumb1).
2788 // * Not callee-saved, so must be one of r0-r3 or r12.
2789 // * Not used to hold an argument to the tail-called function, which might be
2790 // in r0-r3.
2791 // * Not used to hold the return address authentication code, which is in r12
2792 // if enabled.
2793 // Sometimes, no register matches all of these conditions, so we can't do a
2794 // tail-call.
2795 if (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect) {
2796 SmallSet<MCPhysReg, 5> AddressRegisters = {ARM::R0, ARM::R1, ARM::R2,
2797 ARM::R3};
2798 if (!(Subtarget->isThumb1Only() ||
2799 MF.getInfo<ARMFunctionInfo>()->shouldSignReturnAddress(true)))
2800 AddressRegisters.insert(ARM::R12);
2801 for (const CCValAssign &AL : ArgLocs)
2802 if (AL.isRegLoc())
2803 AddressRegisters.erase(AL.getLocReg());
2804 if (AddressRegisters.empty()) {
2805 LLVM_DEBUG(dbgs() << "false (no reg to hold function pointer)\n");
2806 return false;
2807 }
2808 }
2809
2810 // Look for obvious safe cases to perform tail call optimization that do not
2811 // require ABI changes. This is what gcc calls sibcall.
2812
2813 // Exception-handling functions need a special set of instructions to indicate
2814 // a return to the hardware. Tail-calling another function would probably
2815 // break this.
2816 if (CallerF.hasFnAttribute("interrupt")) {
2817 LLVM_DEBUG(dbgs() << "false (interrupt attribute)\n");
2818 return false;
2819 }
2820
2821 if (canGuaranteeTCO(CalleeCC,
2822 getTargetMachine().Options.GuaranteedTailCallOpt)) {
2823 LLVM_DEBUG(dbgs() << (CalleeCC == CallerCC ? "true" : "false")
2824 << " (guaranteed tail-call CC)\n");
2825 return CalleeCC == CallerCC;
2826 }
2827
2828 // Also avoid sibcall optimization if either caller or callee uses struct
2829 // return semantics.
2830 bool isCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
2831 bool isCallerStructRet = MF.getFunction().hasStructRetAttr();
2832 if (isCalleeStructRet != isCallerStructRet) {
2833 LLVM_DEBUG(dbgs() << "false (struct-ret)\n");
2834 return false;
2835 }
2836
2837 // Externally-defined functions with weak linkage should not be
2838 // tail-called on ARM when the OS does not support dynamic
2839 // pre-emption of symbols, as the AAELF spec requires normal calls
2840 // to undefined weak functions to be replaced with a NOP or jump to the
2841 // next instruction. The behaviour of branch instructions in this
2842 // situation (as used for tail calls) is implementation-defined, so we
2843 // cannot rely on the linker replacing the tail call with a return.
2844 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2845 const GlobalValue *GV = G->getGlobal();
2846 const Triple &TT = getTargetMachine().getTargetTriple();
2847 if (GV->hasExternalWeakLinkage() &&
2848 (!TT.isOSWindows() || TT.isOSBinFormatELF() ||
2849 TT.isOSBinFormatMachO())) {
2850 LLVM_DEBUG(dbgs() << "false (external weak linkage)\n");
2851 return false;
2852 }
2853 }
2854
2855 // Check that the call results are passed in the same way.
2856 LLVMContext &C = *DAG.getContext();
2858 getEffectiveCallingConv(CalleeCC, isVarArg),
2859 getEffectiveCallingConv(CallerCC, CallerF.isVarArg()), MF, C, Ins,
2860 CCAssignFnForReturn(CalleeCC, isVarArg),
2861 CCAssignFnForReturn(CallerCC, CallerF.isVarArg()))) {
2862 LLVM_DEBUG(dbgs() << "false (incompatible results)\n");
2863 return false;
2864 }
2865 // The callee has to preserve all registers the caller needs to preserve.
2866 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2867 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2868 if (CalleeCC != CallerCC) {
2869 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2870 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) {
2871 LLVM_DEBUG(dbgs() << "false (not all registers preserved)\n");
2872 return false;
2873 }
2874 }
2875
2876 // If Caller's vararg argument has been split between registers and stack, do
2877 // not perform tail call, since part of the argument is in caller's local
2878 // frame.
2879 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2880 if (CLI.IsVarArg && AFI_Caller->getArgRegsSaveSize()) {
2881 LLVM_DEBUG(dbgs() << "false (arg reg save area)\n");
2882 return false;
2883 }
2884
2885 // If the callee takes no arguments then go on to check the results of the
2886 // call.
2887 const MachineRegisterInfo &MRI = MF.getRegInfo();
2888 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) {
2889 LLVM_DEBUG(dbgs() << "false (parameters in CSRs do not match)\n");
2890 return false;
2891 }
2892
2893 // If the stack arguments for this call do not fit into our own save area then
2894 // the call cannot be made tail.
2895 if (CCInfo.getStackSize() > AFI_Caller->getArgumentStackSize())
2896 return false;
2897
2898 LLVM_DEBUG(dbgs() << "true\n");
2899 return true;
2900}
2901
2902bool
2903ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2904 MachineFunction &MF, bool isVarArg,
2906 LLVMContext &Context, const Type *RetTy) const {
2908 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2909 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2910}
2911
2913 const SDLoc &DL, SelectionDAG &DAG) {
2914 const MachineFunction &MF = DAG.getMachineFunction();
2915 const Function &F = MF.getFunction();
2916
2917 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2918
2919 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2920 // version of the "preferred return address". These offsets affect the return
2921 // instruction if this is a return from PL1 without hypervisor extensions.
2922 // IRQ/FIQ: +4 "subs pc, lr, #4"
2923 // SWI: 0 "subs pc, lr, #0"
2924 // ABORT: +4 "subs pc, lr, #4"
2925 // UNDEF: +4/+2 "subs pc, lr, #0"
2926 // UNDEF varies depending on where the exception came from ARM or Thumb
2927 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2928
2929 int64_t LROffset;
2930 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2931 IntKind == "ABORT")
2932 LROffset = 4;
2933 else if (IntKind == "SWI" || IntKind == "UNDEF")
2934 LROffset = 0;
2935 else
2936 report_fatal_error("Unsupported interrupt attribute. If present, value "
2937 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2938
2939 RetOps.insert(RetOps.begin() + 1,
2940 DAG.getConstant(LROffset, DL, MVT::i32, false));
2941
2942 return DAG.getNode(ARMISD::INTRET_GLUE, DL, MVT::Other, RetOps);
2943}
2944
2945SDValue
2946ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2947 bool isVarArg,
2949 const SmallVectorImpl<SDValue> &OutVals,
2950 const SDLoc &dl, SelectionDAG &DAG) const {
2951 // CCValAssign - represent the assignment of the return value to a location.
2953
2954 // CCState - Info about the registers and stack slots.
2955 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2956 *DAG.getContext());
2957
2958 // Analyze outgoing return values.
2959 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2960
2961 SDValue Glue;
2963 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2964 bool isLittleEndian = Subtarget->isLittle();
2965
2967 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2968 AFI->setReturnRegsCount(RVLocs.size());
2969
2970 // Report error if cmse entry function returns structure through first ptr arg.
2971 if (AFI->isCmseNSEntryFunction() && MF.getFunction().hasStructRetAttr()) {
2972 // Note: using an empty SDLoc(), as the first line of the function is a
2973 // better place to report than the last line.
2974 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
2976 "secure entry function would return value through pointer",
2977 SDLoc().getDebugLoc()));
2978 }
2979
2980 // Copy the result values into the output registers.
2981 for (unsigned i = 0, realRVLocIdx = 0;
2982 i != RVLocs.size();
2983 ++i, ++realRVLocIdx) {
2984 CCValAssign &VA = RVLocs[i];
2985 assert(VA.isRegLoc() && "Can only return in registers!");
2986
2987 SDValue Arg = OutVals[realRVLocIdx];
2988 bool ReturnF16 = false;
2989
2990 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2991 // Half-precision return values can be returned like this:
2992 //
2993 // t11 f16 = fadd ...
2994 // t12: i16 = bitcast t11
2995 // t13: i32 = zero_extend t12
2996 // t14: f32 = bitcast t13 <~~~~~~~ Arg
2997 //
2998 // to avoid code generation for bitcasts, we simply set Arg to the node
2999 // that produces the f16 value, t11 in this case.
3000 //
3001 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
3002 SDValue ZE = Arg.getOperand(0);
3003 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
3004 SDValue BC = ZE.getOperand(0);
3005 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
3006 Arg = BC.getOperand(0);
3007 ReturnF16 = true;
3008 }
3009 }
3010 }
3011 }
3012
3013 switch (VA.getLocInfo()) {
3014 default: llvm_unreachable("Unknown loc info!");
3015 case CCValAssign::Full: break;
3016 case CCValAssign::BCvt:
3017 if (!ReturnF16)
3018 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3019 break;
3020 }
3021
3022 // Mask f16 arguments if this is a CMSE nonsecure entry.
3023 auto RetVT = Outs[realRVLocIdx].ArgVT;
3024 if (AFI->isCmseNSEntryFunction() && (RetVT == MVT::f16)) {
3025 if (VA.needsCustom() && VA.getValVT() == MVT::f16) {
3026 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
3027 } else {
3028 auto LocBits = VA.getLocVT().getSizeInBits();
3029 auto MaskValue = APInt::getLowBitsSet(LocBits, RetVT.getSizeInBits());
3030 SDValue Mask =
3031 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
3032 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
3033 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
3034 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3035 }
3036 }
3037
3038 if (VA.needsCustom() &&
3039 (VA.getLocVT() == MVT::v2f64 || VA.getLocVT() == MVT::f64)) {
3040 if (VA.getLocVT() == MVT::v2f64) {
3041 // Extract the first half and return it in two registers.
3042 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3043 DAG.getConstant(0, dl, MVT::i32));
3044 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
3045 DAG.getVTList(MVT::i32, MVT::i32), Half);
3046
3047 Chain =
3048 DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3049 HalfGPRs.getValue(isLittleEndian ? 0 : 1), Glue);
3050 Glue = Chain.getValue(1);
3051 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3052 VA = RVLocs[++i]; // skip ahead to next loc
3053 Chain =
3054 DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3055 HalfGPRs.getValue(isLittleEndian ? 1 : 0), Glue);
3056 Glue = Chain.getValue(1);
3057 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3058 VA = RVLocs[++i]; // skip ahead to next loc
3059
3060 // Extract the 2nd half and fall through to handle it as an f64 value.
3061 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3062 DAG.getConstant(1, dl, MVT::i32));
3063 }
3064 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
3065 // available.
3066 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
3067 DAG.getVTList(MVT::i32, MVT::i32), Arg);
3068 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3069 fmrrd.getValue(isLittleEndian ? 0 : 1), Glue);
3070 Glue = Chain.getValue(1);
3071 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3072 VA = RVLocs[++i]; // skip ahead to next loc
3073 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3074 fmrrd.getValue(isLittleEndian ? 1 : 0), Glue);
3075 } else
3076 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Glue);
3077
3078 // Guarantee that all emitted copies are
3079 // stuck together, avoiding something bad.
3080 Glue = Chain.getValue(1);
3081 RetOps.push_back(DAG.getRegister(
3082 VA.getLocReg(), ReturnF16 ? Arg.getValueType() : VA.getLocVT()));
3083 }
3084 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
3085 const MCPhysReg *I =
3086 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3087 if (I) {
3088 for (; *I; ++I) {
3089 if (ARM::GPRRegClass.contains(*I))
3090 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
3091 else if (ARM::DPRRegClass.contains(*I))
3093 else
3094 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3095 }
3096 }
3097
3098 // Update chain and glue.
3099 RetOps[0] = Chain;
3100 if (Glue.getNode())
3101 RetOps.push_back(Glue);
3102
3103 // CPUs which aren't M-class use a special sequence to return from
3104 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
3105 // though we use "subs pc, lr, #N").
3106 //
3107 // M-class CPUs actually use a normal return sequence with a special
3108 // (hardware-provided) value in LR, so the normal code path works.
3109 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
3110 !Subtarget->isMClass()) {
3111 if (Subtarget->isThumb1Only())
3112 report_fatal_error("interrupt attribute is not supported in Thumb1");
3113 return LowerInterruptReturn(RetOps, dl, DAG);
3114 }
3115
3116 unsigned RetNode =
3117 AFI->isCmseNSEntryFunction() ? ARMISD::SERET_GLUE : ARMISD::RET_GLUE;
3118 return DAG.getNode(RetNode, dl, MVT::Other, RetOps);
3119}
3120
3121bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
3122 if (N->getNumValues() != 1)
3123 return false;
3124 if (!N->hasNUsesOfValue(1, 0))
3125 return false;
3126
3127 SDValue TCChain = Chain;
3128 SDNode *Copy = *N->user_begin();
3129 if (Copy->getOpcode() == ISD::CopyToReg) {
3130 // If the copy has a glue operand, we conservatively assume it isn't safe to
3131 // perform a tail call.
3132 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3133 return false;
3134 TCChain = Copy->getOperand(0);
3135 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
3136 SDNode *VMov = Copy;
3137 // f64 returned in a pair of GPRs.
3138 SmallPtrSet<SDNode*, 2> Copies;
3139 for (SDNode *U : VMov->users()) {
3140 if (U->getOpcode() != ISD::CopyToReg)
3141 return false;
3142 Copies.insert(U);
3143 }
3144 if (Copies.size() > 2)
3145 return false;
3146
3147 for (SDNode *U : VMov->users()) {
3148 SDValue UseChain = U->getOperand(0);
3149 if (Copies.count(UseChain.getNode()))
3150 // Second CopyToReg
3151 Copy = U;
3152 else {
3153 // We are at the top of this chain.
3154 // If the copy has a glue operand, we conservatively assume it
3155 // isn't safe to perform a tail call.
3156 if (U->getOperand(U->getNumOperands() - 1).getValueType() == MVT::Glue)
3157 return false;
3158 // First CopyToReg
3159 TCChain = UseChain;
3160 }
3161 }
3162 } else if (Copy->getOpcode() == ISD::BITCAST) {
3163 // f32 returned in a single GPR.
3164 if (!Copy->hasOneUse())
3165 return false;
3166 Copy = *Copy->user_begin();
3167 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
3168 return false;
3169 // If the copy has a glue operand, we conservatively assume it isn't safe to
3170 // perform a tail call.
3171 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3172 return false;
3173 TCChain = Copy->getOperand(0);
3174 } else {
3175 return false;
3176 }
3177
3178 bool HasRet = false;
3179 for (const SDNode *U : Copy->users()) {
3180 if (U->getOpcode() != ARMISD::RET_GLUE &&
3181 U->getOpcode() != ARMISD::INTRET_GLUE)
3182 return false;
3183 HasRet = true;
3184 }
3185
3186 if (!HasRet)
3187 return false;
3188
3189 Chain = TCChain;
3190 return true;
3191}
3192
3193bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3194 if (!Subtarget->supportsTailCall())
3195 return false;
3196
3197 if (!CI->isTailCall())
3198 return false;
3199
3200 return true;
3201}
3202
3203// Trying to write a 64 bit value so need to split into two 32 bit values first,
3204// and pass the lower and high parts through.
3206 SDLoc DL(Op);
3207 SDValue WriteValue = Op->getOperand(2);
3208
3209 // This function is only supposed to be called for i64 type argument.
3210 assert(WriteValue.getValueType() == MVT::i64
3211 && "LowerWRITE_REGISTER called for non-i64 type argument.");
3212
3213 SDValue Lo, Hi;
3214 std::tie(Lo, Hi) = DAG.SplitScalar(WriteValue, DL, MVT::i32, MVT::i32);
3215 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
3216 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
3217}
3218
3219// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3220// their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
3221// one of the above mentioned nodes. It has to be wrapped because otherwise
3222// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3223// be used to form addressing mode. These wrapped nodes will be selected
3224// into MOVi.
3225SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
3226 SelectionDAG &DAG) const {
3227 EVT PtrVT = Op.getValueType();
3228 // FIXME there is no actual debug info here
3229 SDLoc dl(Op);
3230 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3231 SDValue Res;
3232
3233 // When generating execute-only code Constant Pools must be promoted to the
3234 // global data section. It's a bit ugly that we can't share them across basic
3235 // blocks, but this way we guarantee that execute-only behaves correct with
3236 // position-independent addressing modes.
3237 if (Subtarget->genExecuteOnly()) {
3238 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3239 auto *T = CP->getType();
3240 auto C = const_cast<Constant*>(CP->getConstVal());
3241 auto M = DAG.getMachineFunction().getFunction().getParent();
3242 auto GV = new GlobalVariable(
3243 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
3244 Twine(DAG.getDataLayout().getInternalSymbolPrefix()) + "CP" +
3245 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
3246 Twine(AFI->createPICLabelUId()));
3247 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3248 return LowerGlobalAddress(GA, DAG);
3249 }
3250
3251 // The 16-bit ADR instruction can only encode offsets that are multiples of 4,
3252 // so we need to align to at least 4 bytes when we don't have 32-bit ADR.
3253 Align CPAlign = CP->getAlign();
3254 if (Subtarget->isThumb1Only())
3255 CPAlign = std::max(CPAlign, Align(4));
3257 Res =
3258 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CPAlign);
3259 else
3260 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CPAlign);
3261 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
3262}
3263
3265 // If we don't have a 32-bit pc-relative branch instruction then the jump
3266 // table consists of block addresses. Usually this is inline, but for
3267 // execute-only it must be placed out-of-line.
3268 if (Subtarget->genExecuteOnly() && !Subtarget->hasV8MBaselineOps())
3271}
3272
3273SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
3274 SelectionDAG &DAG) const {
3277 unsigned ARMPCLabelIndex = 0;
3278 SDLoc DL(Op);
3279 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3280 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3281 SDValue CPAddr;
3282 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3283 if (!IsPositionIndependent) {
3284 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, Align(4));
3285 } else {
3286 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3287 ARMPCLabelIndex = AFI->createPICLabelUId();
3289 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3290 ARMCP::CPBlockAddress, PCAdj);
3291 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3292 }
3293 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3294 SDValue Result = DAG.getLoad(
3295 PtrVT, DL, DAG.getEntryNode(), CPAddr,
3297 if (!IsPositionIndependent)
3298 return Result;
3299 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3300 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3301}
3302
3303/// Convert a TLS address reference into the correct sequence of loads
3304/// and calls to compute the variable's address for Darwin, and return an
3305/// SDValue containing the final node.
3306
3307/// Darwin only has one TLS scheme which must be capable of dealing with the
3308/// fully general situation, in the worst case. This means:
3309/// + "extern __thread" declaration.
3310/// + Defined in a possibly unknown dynamic library.
3311///
3312/// The general system is that each __thread variable has a [3 x i32] descriptor
3313/// which contains information used by the runtime to calculate the address. The
3314/// only part of this the compiler needs to know about is the first word, which
3315/// contains a function pointer that must be called with the address of the
3316/// entire descriptor in "r0".
3317///
3318/// Since this descriptor may be in a different unit, in general access must
3319/// proceed along the usual ARM rules. A common sequence to produce is:
3320///
3321/// movw rT1, :lower16:_var$non_lazy_ptr
3322/// movt rT1, :upper16:_var$non_lazy_ptr
3323/// ldr r0, [rT1]
3324/// ldr rT2, [r0]
3325/// blx rT2
3326/// [...address now in r0...]
3327SDValue
3328ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3329 SelectionDAG &DAG) const {
3330 assert(getTargetMachine().getTargetTriple().isOSDarwin() &&
3331 "This function expects a Darwin target");
3332 SDLoc DL(Op);
3333
3334 // First step is to get the address of the actua global symbol. This is where
3335 // the TLS descriptor lives.
3336 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3337
3338 // The first entry in the descriptor is a function pointer that we must call
3339 // to obtain the address of the variable.
3340 SDValue Chain = DAG.getEntryNode();
3341 SDValue FuncTLVGet = DAG.getLoad(
3342 MVT::i32, DL, Chain, DescAddr,
3346 Chain = FuncTLVGet.getValue(1);
3347
3349 MachineFrameInfo &MFI = F.getFrameInfo();
3350 MFI.setAdjustsStack(true);
3351
3352 // TLS calls preserve all registers except those that absolutely must be
3353 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3354 // silly).
3355 auto TRI =
3357 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3358 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3359
3360 // Finally, we can make the call. This is just a degenerate version of a
3361 // normal AArch64 call node: r0 takes the address of the descriptor, and
3362 // returns the address of the variable in this thread.
3363 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3364 Chain =
3365 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3366 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3367 DAG.getRegisterMask(Mask), Chain.getValue(1));
3368 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3369}
3370
3371SDValue
3372ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3373 SelectionDAG &DAG) const {
3374 assert(getTargetMachine().getTargetTriple().isOSWindows() &&
3375 "Windows specific TLS lowering");
3376
3377 SDValue Chain = DAG.getEntryNode();
3378 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3379 SDLoc DL(Op);
3380
3381 // Load the current TEB (thread environment block)
3382 SDValue Ops[] = {Chain,
3383 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3384 DAG.getTargetConstant(15, DL, MVT::i32),
3385 DAG.getTargetConstant(0, DL, MVT::i32),
3386 DAG.getTargetConstant(13, DL, MVT::i32),
3387 DAG.getTargetConstant(0, DL, MVT::i32),
3388 DAG.getTargetConstant(2, DL, MVT::i32)};
3389 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3390 DAG.getVTList(MVT::i32, MVT::Other), Ops);
3391
3392 SDValue TEB = CurrentTEB.getValue(0);
3393 Chain = CurrentTEB.getValue(1);
3394
3395 // Load the ThreadLocalStoragePointer from the TEB
3396 // A pointer to the TLS array is located at offset 0x2c from the TEB.
3397 SDValue TLSArray =
3398 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3399 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3400
3401 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3402 // offset into the TLSArray.
3403
3404 // Load the TLS index from the C runtime
3405 SDValue TLSIndex =
3406 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3407 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3408 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3409
3410 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3411 DAG.getConstant(2, DL, MVT::i32));
3412 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3413 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3414 MachinePointerInfo());
3415
3416 // Get the offset of the start of the .tls section (section base)
3417 const auto *GA = cast<GlobalAddressSDNode>(Op);
3418 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3419 SDValue Offset = DAG.getLoad(
3420 PtrVT, DL, Chain,
3421 DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3422 DAG.getTargetConstantPool(CPV, PtrVT, Align(4))),
3424
3425 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3426}
3427
3428// Lower ISD::GlobalTLSAddress using the "general dynamic" model
3429SDValue
3430ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3431 SelectionDAG &DAG) const {
3432 SDLoc dl(GA);
3433 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3434 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3436 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3437 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3438 ARMConstantPoolValue *CPV =
3439 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3440 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3441 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3442 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3443 Argument = DAG.getLoad(
3444 PtrVT, dl, DAG.getEntryNode(), Argument,
3446 SDValue Chain = Argument.getValue(1);
3447
3448 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3449 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3450
3451 // call __tls_get_addr.
3453 Args.emplace_back(Argument, Type::getInt32Ty(*DAG.getContext()));
3454
3455 // FIXME: is there useful debug info available here?
3456 TargetLowering::CallLoweringInfo CLI(DAG);
3457 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3459 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3460
3461 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3462 return CallResult.first;
3463}
3464
3465// Lower ISD::GlobalTLSAddress using the "initial exec" or
3466// "local exec" model.
3467SDValue
3468ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3469 SelectionDAG &DAG,
3470 TLSModel::Model model) const {
3471 const GlobalValue *GV = GA->getGlobal();
3472 SDLoc dl(GA);
3474 SDValue Chain = DAG.getEntryNode();
3475 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3476 // Get the Thread Pointer
3477 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3478
3479 if (model == TLSModel::InitialExec) {
3481 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3482 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3483 // Initial exec model.
3484 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3485 ARMConstantPoolValue *CPV =
3486 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3488 true);
3489 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3490 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3491 Offset = DAG.getLoad(
3492 PtrVT, dl, Chain, Offset,
3494 Chain = Offset.getValue(1);
3495
3496 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3497 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3498
3499 Offset = DAG.getLoad(
3500 PtrVT, dl, Chain, Offset,
3502 } else {
3503 // local exec model
3504 assert(model == TLSModel::LocalExec);
3505 ARMConstantPoolValue *CPV =
3507 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3508 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3509 Offset = DAG.getLoad(
3510 PtrVT, dl, Chain, Offset,
3512 }
3513
3514 // The address of the thread local variable is the add of the thread
3515 // pointer with the offset of the variable.
3516 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3517}
3518
3519SDValue
3520ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3521 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3522 if (DAG.getTarget().useEmulatedTLS())
3523 return LowerToTLSEmulatedModel(GA, DAG);
3524
3525 const Triple &TT = getTargetMachine().getTargetTriple();
3526 if (TT.isOSDarwin())
3527 return LowerGlobalTLSAddressDarwin(Op, DAG);
3528
3529 if (TT.isOSWindows())
3530 return LowerGlobalTLSAddressWindows(Op, DAG);
3531
3532 // TODO: implement the "local dynamic" model
3533 assert(TT.isOSBinFormatELF() && "Only ELF implemented here");
3535
3536 switch (model) {
3539 return LowerToTLSGeneralDynamicModel(GA, DAG);
3542 return LowerToTLSExecModels(GA, DAG, model);
3543 }
3544 llvm_unreachable("bogus TLS model");
3545}
3546
3547/// Return true if all users of V are within function F, looking through
3548/// ConstantExprs.
3549static bool allUsersAreInFunction(const Value *V, const Function *F) {
3550 SmallVector<const User*,4> Worklist(V->users());
3551 while (!Worklist.empty()) {
3552 auto *U = Worklist.pop_back_val();
3553 if (isa<ConstantExpr>(U)) {
3554 append_range(Worklist, U->users());
3555 continue;
3556 }
3557
3558 auto *I = dyn_cast<Instruction>(U);
3559 if (!I || I->getParent()->getParent() != F)
3560 return false;
3561 }
3562 return true;
3563}
3564
3566 const GlobalValue *GV, SelectionDAG &DAG,
3567 EVT PtrVT, const SDLoc &dl) {
3568 // If we're creating a pool entry for a constant global with unnamed address,
3569 // and the global is small enough, we can emit it inline into the constant pool
3570 // to save ourselves an indirection.
3571 //
3572 // This is a win if the constant is only used in one function (so it doesn't
3573 // need to be duplicated) or duplicating the constant wouldn't increase code
3574 // size (implying the constant is no larger than 4 bytes).
3575 const Function &F = DAG.getMachineFunction().getFunction();
3576
3577 // We rely on this decision to inline being idempotent and unrelated to the
3578 // use-site. We know that if we inline a variable at one use site, we'll
3579 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3580 // doesn't know about this optimization, so bail out if it's enabled else
3581 // we could decide to inline here (and thus never emit the GV) but require
3582 // the GV from fast-isel generated code.
3585 return SDValue();
3586
3587 auto *GVar = dyn_cast<GlobalVariable>(GV);
3588 if (!GVar || !GVar->hasInitializer() ||
3589 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3590 !GVar->hasLocalLinkage())
3591 return SDValue();
3592
3593 // If we inline a value that contains relocations, we move the relocations
3594 // from .data to .text. This is not allowed in position-independent code.
3595 auto *Init = GVar->getInitializer();
3596 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3597 Init->needsDynamicRelocation())
3598 return SDValue();
3599
3600 // The constant islands pass can only really deal with alignment requests
3601 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3602 // any type wanting greater alignment requirements than 4 bytes. We also
3603 // can only promote constants that are multiples of 4 bytes in size or
3604 // are paddable to a multiple of 4. Currently we only try and pad constants
3605 // that are strings for simplicity.
3606 auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3607 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3608 Align PrefAlign = DAG.getDataLayout().getPreferredAlign(GVar);
3609 unsigned RequiredPadding = 4 - (Size % 4);
3610 bool PaddingPossible =
3611 RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3612 if (!PaddingPossible || PrefAlign > 4 || Size > ConstpoolPromotionMaxSize ||
3613 Size == 0)
3614 return SDValue();
3615
3616 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3618 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3619
3620 // We can't bloat the constant pool too much, else the ConstantIslands pass
3621 // may fail to converge. If we haven't promoted this global yet (it may have
3622 // multiple uses), and promoting it would increase the constant pool size (Sz
3623 // > 4), ensure we have space to do so up to MaxTotal.
3624 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3625 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3627 return SDValue();
3628
3629 // This is only valid if all users are in a single function; we can't clone
3630 // the constant in general. The LLVM IR unnamed_addr allows merging
3631 // constants, but not cloning them.
3632 //
3633 // We could potentially allow cloning if we could prove all uses of the
3634 // constant in the current function don't care about the address, like
3635 // printf format strings. But that isn't implemented for now.
3636 if (!allUsersAreInFunction(GVar, &F))
3637 return SDValue();
3638
3639 // We're going to inline this global. Pad it out if needed.
3640 if (RequiredPadding != 4) {
3641 StringRef S = CDAInit->getAsString();
3642
3644 std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3645 while (RequiredPadding--)
3646 V.push_back(0);
3648 }
3649
3650 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3651 SDValue CPAddr = DAG.getTargetConstantPool(CPVal, PtrVT, Align(4));
3652 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3655 PaddedSize - 4);
3656 }
3657 ++NumConstpoolPromoted;
3658 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3659}
3660
3662 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3663 if (!(GV = GA->getAliaseeObject()))
3664 return false;
3665 if (const auto *V = dyn_cast<GlobalVariable>(GV))
3666 return V->isConstant();
3667 return isa<Function>(GV);
3668}
3669
3670SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3671 SelectionDAG &DAG) const {
3672 switch (Subtarget->getTargetTriple().getObjectFormat()) {
3673 default: llvm_unreachable("unknown object format");
3674 case Triple::COFF:
3675 return LowerGlobalAddressWindows(Op, DAG);
3676 case Triple::ELF:
3677 return LowerGlobalAddressELF(Op, DAG);
3678 case Triple::MachO:
3679 return LowerGlobalAddressDarwin(Op, DAG);
3680 }
3681}
3682
3683SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3684 SelectionDAG &DAG) const {
3685 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3686 SDLoc dl(Op);
3687 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3688 bool IsRO = isReadOnly(GV);
3689
3690 // promoteToConstantPool only if not generating XO text section
3691 if (GV->isDSOLocal() && !Subtarget->genExecuteOnly())
3692 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3693 return V;
3694
3695 if (isPositionIndependent()) {
3697 GV, dl, PtrVT, 0, GV->isDSOLocal() ? 0 : ARMII::MO_GOT);
3698 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3699 if (!GV->isDSOLocal())
3700 Result =
3701 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3703 return Result;
3704 } else if (Subtarget->isROPI() && IsRO) {
3705 // PC-relative.
3706 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3707 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3708 return Result;
3709 } else if (Subtarget->isRWPI() && !IsRO) {
3710 // SB-relative.
3711 SDValue RelAddr;
3712 if (Subtarget->useMovt()) {
3713 ++NumMovwMovt;
3714 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3715 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3716 } else { // use literal pool for address constant
3717 ARMConstantPoolValue *CPV =
3719 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3720 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3721 RelAddr = DAG.getLoad(
3722 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3724 }
3725 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3726 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3727 return Result;
3728 }
3729
3730 // If we have T2 ops, we can materialize the address directly via movt/movw
3731 // pair. This is always cheaper. If need to generate Execute Only code, and we
3732 // only have Thumb1 available, we can't use a constant pool and are forced to
3733 // use immediate relocations.
3734 if (Subtarget->useMovt() || Subtarget->genExecuteOnly()) {
3735 if (Subtarget->useMovt())
3736 ++NumMovwMovt;
3737 // FIXME: Once remat is capable of dealing with instructions with register
3738 // operands, expand this into two nodes.
3739 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3740 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3741 } else {
3742 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, Align(4));
3743 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3744 return DAG.getLoad(
3745 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3747 }
3748}
3749
3750SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3751 SelectionDAG &DAG) const {
3752 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3753 "ROPI/RWPI not currently supported for Darwin");
3754 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3755 SDLoc dl(Op);
3756 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3757
3758 if (Subtarget->useMovt())
3759 ++NumMovwMovt;
3760
3761 // FIXME: Once remat is capable of dealing with instructions with register
3762 // operands, expand this into multiple nodes
3763 unsigned Wrapper =
3764 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3765
3766 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3767 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3768
3769 if (Subtarget->isGVIndirectSymbol(GV))
3770 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3772 return Result;
3773}
3774
3775SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3776 SelectionDAG &DAG) const {
3777 assert(getTargetMachine().getTargetTriple().isOSWindows() &&
3778 "non-Windows COFF is not supported");
3779 assert(Subtarget->useMovt() &&
3780 "Windows on ARM expects to use movw/movt");
3781 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3782 "ROPI/RWPI not currently supported for Windows");
3783
3784 const TargetMachine &TM = getTargetMachine();
3785 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3786 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3787 if (GV->hasDLLImportStorageClass())
3788 TargetFlags = ARMII::MO_DLLIMPORT;
3789 else if (!TM.shouldAssumeDSOLocal(GV))
3790 TargetFlags = ARMII::MO_COFFSTUB;
3791 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3793 SDLoc DL(Op);
3794
3795 ++NumMovwMovt;
3796
3797 // FIXME: Once remat is capable of dealing with instructions with register
3798 // operands, expand this into two nodes.
3799 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3800 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3801 TargetFlags));
3802 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3803 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3805 return Result;
3806}
3807
3808SDValue
3809ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3810 SDLoc dl(Op);
3811 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3812 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3813 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3814 Op.getOperand(1), Val);
3815}
3816
3817SDValue
3818ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3819 SDLoc dl(Op);
3820 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3821 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3822}
3823
3824SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3825 SelectionDAG &DAG) const {
3826 SDLoc dl(Op);
3827 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3828 Op.getOperand(0));
3829}
3830
3831SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3832 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3833 unsigned IntNo =
3834 Op.getConstantOperandVal(Op.getOperand(0).getValueType() == MVT::Other);
3835 switch (IntNo) {
3836 default:
3837 return SDValue(); // Don't custom lower most intrinsics.
3838 case Intrinsic::arm_gnu_eabi_mcount: {
3840 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3841 SDLoc dl(Op);
3842 SDValue Chain = Op.getOperand(0);
3843 // call "\01__gnu_mcount_nc"
3844 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3845 const uint32_t *Mask =
3847 assert(Mask && "Missing call preserved mask for calling convention");
3848 // Mark LR an implicit live-in.
3849 Register Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3850 SDValue ReturnAddress =
3851 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
3852 constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue};
3853 SDValue Callee =
3854 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
3856 if (Subtarget->isThumb())
3857 return SDValue(
3858 DAG.getMachineNode(
3859 ARM::tBL_PUSHLR, dl, ResultTys,
3860 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
3861 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
3862 0);
3863 return SDValue(
3864 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
3865 {ReturnAddress, Callee, RegisterMask, Chain}),
3866 0);
3867 }
3868 }
3869}
3870
3871SDValue
3872ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3873 const ARMSubtarget *Subtarget) const {
3874 unsigned IntNo = Op.getConstantOperandVal(0);
3875 SDLoc dl(Op);
3876 switch (IntNo) {
3877 default: return SDValue(); // Don't custom lower most intrinsics.
3878 case Intrinsic::localaddress: {
3879 const MachineFunction &MF = DAG.getMachineFunction();
3880 const auto *RegInfo = Subtarget->getRegisterInfo();
3881 unsigned Reg = RegInfo->getLocalAddressRegister(MF);
3882 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
3883 Op.getSimpleValueType());
3884 }
3885 case Intrinsic::eh_recoverfp: {
3886 SDValue FnOp = Op.getOperand(1);
3887 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
3888 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
3889 if (!Fn)
3891 "llvm.eh.recoverfp must take a function as the first argument");
3892 const auto *RegInfo = Subtarget->getRegisterInfo();
3893 Register BaseReg = RegInfo->getBaseRegister();
3895 MachineBasicBlock &MBB = *MF.begin();
3896 if (!MBB.isLiveIn(BaseReg))
3897 MBB.addLiveIn(BaseReg);
3898 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3899 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, BaseReg, PtrVT);
3900 }
3901 case Intrinsic::thread_pointer: {
3902 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3903 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3904 }
3905 case Intrinsic::arm_cls: {
3906 // Note: arm_cls and arm_cls64 intrinsics are expanded directly here
3907 // in LowerINTRINSIC_WO_CHAIN since there's no native scalar CLS
3908 // instruction.
3909 const SDValue &Operand = Op.getOperand(1);
3910 const EVT VTy = Op.getValueType();
3911 return DAG.getNode(ISD::CTLS, dl, VTy, Operand);
3912 }
3913 case Intrinsic::arm_cls64: {
3914 // arm_cls64 returns i32 but takes i64 input.
3915 // Use ISD::CTLS for i64 and truncate the result.
3916 SDValue CTLS64 = DAG.getNode(ISD::CTLS, dl, MVT::i64, Op.getOperand(1));
3917 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, CTLS64);
3918 }
3919 case Intrinsic::arm_neon_vcls:
3920 case Intrinsic::arm_mve_vcls: {
3921 // Lower vector CLS intrinsics to ISD::CTLS.
3922 // Vector CTLS is Legal when NEON/MVE is available (set elsewhere).
3923 const EVT VTy = Op.getValueType();
3924 return DAG.getNode(ISD::CTLS, dl, VTy, Op.getOperand(1));
3925 }
3926 case Intrinsic::eh_sjlj_lsda: {
3928 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3929 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3930 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3931 SDValue CPAddr;
3932 bool IsPositionIndependent = isPositionIndependent();
3933 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3934 ARMConstantPoolValue *CPV =
3935 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3936 ARMCP::CPLSDA, PCAdj);
3937 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3938 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3939 SDValue Result = DAG.getLoad(
3940 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3942
3943 if (IsPositionIndependent) {
3944 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3945 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3946 }
3947 return Result;
3948 }
3949 case Intrinsic::arm_neon_vabs:
3950 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3951 Op.getOperand(1));
3952 case Intrinsic::arm_neon_vabds:
3953 if (Op.getValueType().isInteger())
3954 return DAG.getNode(ISD::ABDS, SDLoc(Op), Op.getValueType(),
3955 Op.getOperand(1), Op.getOperand(2));
3956 return SDValue();
3957 case Intrinsic::arm_neon_vabdu:
3958 return DAG.getNode(ISD::ABDU, SDLoc(Op), Op.getValueType(),
3959 Op.getOperand(1), Op.getOperand(2));
3960 case Intrinsic::arm_neon_vmulls:
3961 case Intrinsic::arm_neon_vmullu: {
3962 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3963 ? ARMISD::VMULLs : ARMISD::VMULLu;
3964 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3965 Op.getOperand(1), Op.getOperand(2));
3966 }
3967 case Intrinsic::arm_neon_vminnm:
3968 case Intrinsic::arm_neon_vmaxnm: {
3969 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3970 ? ISD::FMINNUM : ISD::FMAXNUM;
3971 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3972 Op.getOperand(1), Op.getOperand(2));
3973 }
3974 case Intrinsic::arm_neon_vminu:
3975 case Intrinsic::arm_neon_vmaxu: {
3976 if (Op.getValueType().isFloatingPoint())
3977 return SDValue();
3978 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3979 ? ISD::UMIN : ISD::UMAX;
3980 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3981 Op.getOperand(1), Op.getOperand(2));
3982 }
3983 case Intrinsic::arm_neon_vmins:
3984 case Intrinsic::arm_neon_vmaxs: {
3985 // v{min,max}s is overloaded between signed integers and floats.
3986 if (!Op.getValueType().isFloatingPoint()) {
3987 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3988 ? ISD::SMIN : ISD::SMAX;
3989 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3990 Op.getOperand(1), Op.getOperand(2));
3991 }
3992 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3993 ? ISD::FMINIMUM : ISD::FMAXIMUM;
3994 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3995 Op.getOperand(1), Op.getOperand(2));
3996 }
3997 case Intrinsic::arm_neon_vtbl1:
3998 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3999 Op.getOperand(1), Op.getOperand(2));
4000 case Intrinsic::arm_neon_vtbl2:
4001 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
4002 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4003 case Intrinsic::arm_mve_pred_i2v:
4004 case Intrinsic::arm_mve_pred_v2i:
4005 return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(),
4006 Op.getOperand(1));
4007 case Intrinsic::arm_mve_vreinterpretq:
4008 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(Op), Op.getValueType(),
4009 Op.getOperand(1));
4010 case Intrinsic::arm_mve_lsll:
4011 return DAG.getNode(ARMISD::LSLL, SDLoc(Op), Op->getVTList(),
4012 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4013 case Intrinsic::arm_mve_asrl:
4014 return DAG.getNode(ARMISD::ASRL, SDLoc(Op), Op->getVTList(),
4015 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4016 case Intrinsic::arm_mve_vsli:
4017 return DAG.getNode(ARMISD::VSLIIMM, SDLoc(Op), Op->getVTList(),
4018 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4019 case Intrinsic::arm_mve_vsri:
4020 return DAG.getNode(ARMISD::VSRIIMM, SDLoc(Op), Op->getVTList(),
4021 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4022 }
4023}
4024
4026 const ARMSubtarget *Subtarget) {
4027 SDLoc dl(Op);
4028 auto SSID = static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
4029 if (SSID == SyncScope::SingleThread)
4030 return Op;
4031
4032 if (!Subtarget->hasDataBarrier()) {
4033 // Some ARMv6 cpus can support data barriers with an mcr instruction.
4034 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
4035 // here.
4036 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
4037 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
4038 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
4039 DAG.getConstant(0, dl, MVT::i32));
4040 }
4041
4042 AtomicOrdering Ord =
4043 static_cast<AtomicOrdering>(Op.getConstantOperandVal(1));
4045 if (Subtarget->isMClass()) {
4046 // Only a full system barrier exists in the M-class architectures.
4048 } else if (Subtarget->preferISHSTBarriers() &&
4049 Ord == AtomicOrdering::Release) {
4050 // Swift happens to implement ISHST barriers in a way that's compatible with
4051 // Release semantics but weaker than ISH so we'd be fools not to use
4052 // it. Beware: other processors probably don't!
4054 }
4055
4056 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
4057 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
4058 DAG.getConstant(Domain, dl, MVT::i32));
4059}
4060
4062 const ARMSubtarget *Subtarget) {
4063 // ARM pre v5TE and Thumb1 does not have preload instructions.
4064 if (!(Subtarget->isThumb2() ||
4065 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
4066 // Just preserve the chain.
4067 return Op.getOperand(0);
4068
4069 SDLoc dl(Op);
4070 unsigned isRead = ~Op.getConstantOperandVal(2) & 1;
4071 if (!isRead &&
4072 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
4073 // ARMv7 with MP extension has PLDW.
4074 return Op.getOperand(0);
4075
4076 unsigned isData = Op.getConstantOperandVal(4);
4077 if (Subtarget->isThumb()) {
4078 // Invert the bits.
4079 isRead = ~isRead & 1;
4080 isData = ~isData & 1;
4081 }
4082
4083 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
4084 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
4085 DAG.getConstant(isData, dl, MVT::i32));
4086}
4087
4090 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
4091
4092 // vastart just stores the address of the VarArgsFrameIndex slot into the
4093 // memory location argument.
4094 SDLoc dl(Op);
4096 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4097 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4098 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
4099 MachinePointerInfo(SV));
4100}
4101
4102SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
4103 CCValAssign &NextVA,
4104 SDValue &Root,
4105 SelectionDAG &DAG,
4106 const SDLoc &dl) const {
4108 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4109
4110 const TargetRegisterClass *RC;
4111 if (AFI->isThumb1OnlyFunction())
4112 RC = &ARM::tGPRRegClass;
4113 else
4114 RC = &ARM::GPRRegClass;
4115
4116 // Transform the arguments stored in physical registers into virtual ones.
4117 Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4118 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4119
4120 SDValue ArgValue2;
4121 if (NextVA.isMemLoc()) {
4122 MachineFrameInfo &MFI = MF.getFrameInfo();
4123 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
4124
4125 // Create load node to retrieve arguments from the stack.
4126 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4127 ArgValue2 = DAG.getLoad(
4128 MVT::i32, dl, Root, FIN,
4130 } else {
4131 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
4132 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4133 }
4134 if (!Subtarget->isLittle())
4135 std::swap (ArgValue, ArgValue2);
4136 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
4137}
4138
4139// The remaining GPRs hold either the beginning of variable-argument
4140// data, or the beginning of an aggregate passed by value (usually
4141// byval). Either way, we allocate stack slots adjacent to the data
4142// provided by our caller, and store the unallocated registers there.
4143// If this is a variadic function, the va_list pointer will begin with
4144// these values; otherwise, this reassembles a (byval) structure that
4145// was split between registers and memory.
4146// Return: The frame index registers were stored into.
4147int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
4148 const SDLoc &dl, SDValue &Chain,
4149 const Value *OrigArg,
4150 unsigned InRegsParamRecordIdx,
4151 int ArgOffset, unsigned ArgSize) const {
4152 // Currently, two use-cases possible:
4153 // Case #1. Non-var-args function, and we meet first byval parameter.
4154 // Setup first unallocated register as first byval register;
4155 // eat all remained registers
4156 // (these two actions are performed by HandleByVal method).
4157 // Then, here, we initialize stack frame with
4158 // "store-reg" instructions.
4159 // Case #2. Var-args function, that doesn't contain byval parameters.
4160 // The same: eat all remained unallocated registers,
4161 // initialize stack frame.
4162
4164 MachineFrameInfo &MFI = MF.getFrameInfo();
4165 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4166 unsigned RBegin, REnd;
4167 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
4168 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
4169 } else {
4170 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4171 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
4172 REnd = ARM::R4;
4173 }
4174
4175 if (REnd != RBegin)
4176 ArgOffset = -4 * (ARM::R4 - RBegin);
4177
4178 auto PtrVT = getPointerTy(DAG.getDataLayout());
4179 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
4180 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
4181
4183 const TargetRegisterClass *RC =
4184 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
4185
4186 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
4187 Register VReg = MF.addLiveIn(Reg, RC);
4188 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4189 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4190 MachinePointerInfo(OrigArg, 4 * i));
4191 MemOps.push_back(Store);
4192 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
4193 }
4194
4195 if (!MemOps.empty())
4196 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4197 return FrameIndex;
4198}
4199
4200// Setup stack frame, the va_list pointer will start from.
4201void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
4202 const SDLoc &dl, SDValue &Chain,
4203 unsigned ArgOffset,
4204 unsigned TotalArgRegsSaveSize,
4205 bool ForceMutable) const {
4207 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4208
4209 // Try to store any remaining integer argument regs
4210 // to their spots on the stack so that they may be loaded by dereferencing
4211 // the result of va_next.
4212 // If there is no regs to be stored, just point address after last
4213 // argument passed via stack.
4214 int FrameIndex = StoreByValRegs(
4215 CCInfo, DAG, dl, Chain, nullptr, CCInfo.getInRegsParamsCount(),
4216 CCInfo.getStackSize(), std::max(4U, TotalArgRegsSaveSize));
4217 AFI->setVarArgsFrameIndex(FrameIndex);
4218}
4219
4220bool ARMTargetLowering::splitValueIntoRegisterParts(
4221 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
4222 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
4223 EVT ValueVT = Val.getValueType();
4224 if ((ValueVT == MVT::f16 || ValueVT == MVT::bf16) && PartVT == MVT::f32) {
4225 unsigned ValueBits = ValueVT.getSizeInBits();
4226 unsigned PartBits = PartVT.getSizeInBits();
4227 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(ValueBits), Val);
4228 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::getIntegerVT(PartBits), Val);
4229 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
4230 Parts[0] = Val;
4231 return true;
4232 }
4233 return false;
4234}
4235
4236SDValue ARMTargetLowering::joinRegisterPartsIntoValue(
4237 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
4238 MVT PartVT, EVT ValueVT, std::optional<CallingConv::ID> CC) const {
4239 if ((ValueVT == MVT::f16 || ValueVT == MVT::bf16) && PartVT == MVT::f32) {
4240 unsigned ValueBits = ValueVT.getSizeInBits();
4241 unsigned PartBits = PartVT.getSizeInBits();
4242 SDValue Val = Parts[0];
4243
4244 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(PartBits), Val);
4245 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::getIntegerVT(ValueBits), Val);
4246 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
4247 return Val;
4248 }
4249 return SDValue();
4250}
4251
4252SDValue ARMTargetLowering::LowerFormalArguments(
4253 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4254 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4255 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4257 MachineFrameInfo &MFI = MF.getFrameInfo();
4258
4259 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4260
4261 // Assign locations to all of the incoming arguments.
4263 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4264 *DAG.getContext());
4265 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
4266
4268 unsigned CurArgIdx = 0;
4269
4270 // Initially ArgRegsSaveSize is zero.
4271 // Then we increase this value each time we meet byval parameter.
4272 // We also increase this value in case of varargs function.
4273 AFI->setArgRegsSaveSize(0);
4274
4275 // Calculate the amount of stack space that we need to allocate to store
4276 // byval and variadic arguments that are passed in registers.
4277 // We need to know this before we allocate the first byval or variadic
4278 // argument, as they will be allocated a stack slot below the CFA (Canonical
4279 // Frame Address, the stack pointer at entry to the function).
4280 unsigned ArgRegBegin = ARM::R4;
4281 for (const CCValAssign &VA : ArgLocs) {
4282 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
4283 break;
4284
4285 unsigned Index = VA.getValNo();
4286 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
4287 if (!Flags.isByVal())
4288 continue;
4289
4290 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
4291 unsigned RBegin, REnd;
4292 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
4293 ArgRegBegin = std::min(ArgRegBegin, RBegin);
4294
4295 CCInfo.nextInRegsParam();
4296 }
4297 CCInfo.rewindByValRegsInfo();
4298
4299 int lastInsIndex = -1;
4300 if (isVarArg && MFI.hasVAStart()) {
4301 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4302 if (RegIdx != std::size(GPRArgRegs))
4303 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
4304 }
4305
4306 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
4307 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
4308 auto PtrVT = getPointerTy(DAG.getDataLayout());
4309
4310 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4311 CCValAssign &VA = ArgLocs[i];
4312 if (Ins[VA.getValNo()].isOrigArg()) {
4313 std::advance(CurOrigArg,
4314 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
4315 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
4316 }
4317 // Arguments stored in registers.
4318 if (VA.isRegLoc()) {
4319 EVT RegVT = VA.getLocVT();
4320 SDValue ArgValue;
4321
4322 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
4323 // f64 and vector types are split up into multiple registers or
4324 // combinations of registers and stack slots.
4325 SDValue ArgValue1 =
4326 GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4327 VA = ArgLocs[++i]; // skip ahead to next loc
4328 SDValue ArgValue2;
4329 if (VA.isMemLoc()) {
4330 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
4331 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4332 ArgValue2 = DAG.getLoad(
4333 MVT::f64, dl, Chain, FIN,
4335 } else {
4336 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4337 }
4338 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
4339 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4340 ArgValue1, DAG.getIntPtrConstant(0, dl));
4341 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4342 ArgValue2, DAG.getIntPtrConstant(1, dl));
4343 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
4344 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4345 } else {
4346 const TargetRegisterClass *RC;
4347
4348 if (RegVT == MVT::f16 || RegVT == MVT::bf16)
4349 RC = &ARM::HPRRegClass;
4350 else if (RegVT == MVT::f32)
4351 RC = &ARM::SPRRegClass;
4352 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16 ||
4353 RegVT == MVT::v4bf16)
4354 RC = &ARM::DPRRegClass;
4355 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16 ||
4356 RegVT == MVT::v8bf16)
4357 RC = &ARM::QPRRegClass;
4358 else if (RegVT == MVT::i32)
4359 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
4360 : &ARM::GPRRegClass;
4361 else
4362 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
4363
4364 // Transform the arguments in physical registers into virtual ones.
4365 Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4366 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
4367
4368 // If this value is passed in r0 and has the returned attribute (e.g.
4369 // C++ 'structors), record this fact for later use.
4370 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4371 AFI->setPreservesR0();
4372 }
4373 }
4374
4375 // If this is an 8 or 16-bit value, it is really passed promoted
4376 // to 32 bits. Insert an assert[sz]ext to capture this, then
4377 // truncate to the right size.
4378 switch (VA.getLocInfo()) {
4379 default: llvm_unreachable("Unknown loc info!");
4380 case CCValAssign::Full: break;
4381 case CCValAssign::BCvt:
4382 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4383 break;
4384 }
4385
4386 // f16 arguments have their size extended to 4 bytes and passed as if they
4387 // had been copied to the LSBs of a 32-bit register.
4388 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
4389 if (VA.needsCustom() &&
4390 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
4391 ArgValue = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), ArgValue);
4392
4393 // On CMSE Entry Functions, formal integer arguments whose bitwidth is
4394 // less than 32 bits must be sign- or zero-extended in the callee for
4395 // security reasons. Although the ABI mandates an extension done by the
4396 // caller, the latter cannot be trusted to follow the rules of the ABI.
4397 const ISD::InputArg &Arg = Ins[VA.getValNo()];
4398 if (AFI->isCmseNSEntryFunction() && Arg.ArgVT.isScalarInteger() &&
4399 RegVT.isScalarInteger() && Arg.ArgVT.bitsLT(MVT::i32))
4400 ArgValue = handleCMSEValue(ArgValue, Arg, DAG, dl);
4401
4402 InVals.push_back(ArgValue);
4403 } else { // VA.isRegLoc()
4404 // Only arguments passed on the stack should make it here.
4405 assert(VA.isMemLoc());
4406 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4407
4408 int index = VA.getValNo();
4409
4410 // Some Ins[] entries become multiple ArgLoc[] entries.
4411 // Process them only once.
4412 if (index != lastInsIndex)
4413 {
4414 ISD::ArgFlagsTy Flags = Ins[index].Flags;
4415 // FIXME: For now, all byval parameter objects are marked mutable.
4416 // This can be changed with more analysis.
4417 // In case of tail call optimization mark all arguments mutable.
4418 // Since they could be overwritten by lowering of arguments in case of
4419 // a tail call.
4420 if (Flags.isByVal()) {
4421 assert(Ins[index].isOrigArg() &&
4422 "Byval arguments cannot be implicit");
4423 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4424
4425 int FrameIndex = StoreByValRegs(
4426 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4427 VA.getLocMemOffset(), Flags.getByValSize());
4428 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4429 CCInfo.nextInRegsParam();
4430 } else if (VA.needsCustom() && (VA.getValVT() == MVT::f16 ||
4431 VA.getValVT() == MVT::bf16)) {
4432 // f16 and bf16 values are passed in the least-significant half of
4433 // a 4 byte stack slot. This is done as-if the extension was done
4434 // in a 32-bit register, so the actual bytes used for the value
4435 // differ between little and big endian.
4436 assert(VA.getLocVT().getSizeInBits() == 32);
4437 unsigned FIOffset = VA.getLocMemOffset();
4438 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits() / 8,
4439 FIOffset, true);
4440
4441 SDValue Addr = DAG.getFrameIndex(FI, PtrVT);
4442 if (DAG.getDataLayout().isBigEndian())
4443 Addr = DAG.getObjectPtrOffset(dl, Addr, TypeSize::getFixed(2));
4444
4445 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, Addr,
4447 DAG.getMachineFunction(), FI)));
4448
4449 } else {
4450 unsigned FIOffset = VA.getLocMemOffset();
4451 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4452 FIOffset, true);
4453
4454 // Create load nodes to retrieve arguments from the stack.
4455 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4456 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4458 DAG.getMachineFunction(), FI)));
4459 }
4460 lastInsIndex = index;
4461 }
4462 }
4463 }
4464
4465 // varargs
4466 if (isVarArg && MFI.hasVAStart()) {
4467 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getStackSize(),
4468 TotalArgRegsSaveSize);
4469 if (AFI->isCmseNSEntryFunction()) {
4470 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
4472 "secure entry function must not be variadic", dl.getDebugLoc()));
4473 }
4474 }
4475
4476 unsigned StackArgSize = CCInfo.getStackSize();
4477 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4478 if (canGuaranteeTCO(CallConv, TailCallOpt)) {
4479 // The only way to guarantee a tail call is if the callee restores its
4480 // argument area, but it must also keep the stack aligned when doing so.
4481 MaybeAlign StackAlign = DAG.getDataLayout().getStackAlignment();
4482 assert(StackAlign && "data layout string is missing stack alignment");
4483 StackArgSize = alignTo(StackArgSize, *StackAlign);
4484
4485 AFI->setArgumentStackToRestore(StackArgSize);
4486 }
4487 AFI->setArgumentStackSize(StackArgSize);
4488
4489 if (CCInfo.getStackSize() > 0 && AFI->isCmseNSEntryFunction()) {
4490 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
4492 "secure entry function requires arguments on stack", dl.getDebugLoc()));
4493 }
4494
4495 return Chain;
4496}
4497
4498/// isFloatingPointZero - Return true if this is +0.0.
4501 return CFP->getValueAPF().isPosZero();
4502 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4503 // Maybe this has already been legalized into the constant pool?
4504 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4505 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4507 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4508 return CFP->getValueAPF().isPosZero();
4509 }
4510 } else if (Op->getOpcode() == ISD::BITCAST &&
4511 Op->getValueType(0) == MVT::f64) {
4512 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4513 // created by LowerConstantFP().
4514 SDValue BitcastOp = Op->getOperand(0);
4515 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4516 isNullConstant(BitcastOp->getOperand(0)))
4517 return true;
4518 }
4519 return false;
4520}
4521
4523 // 0 - INT_MIN sign wraps, so no signed wrap means cmn is safe.
4524 if (Op->getFlags().hasNoSignedWrap())
4525 return true;
4526
4527 // We can still figure out if the second operand is safe to use
4528 // in a CMN instruction by checking if it is known to be not the minimum
4529 // signed value. If it is not, then we can safely use CMN.
4530 // Note: We can eventually remove this check and simply rely on
4531 // Op->getFlags().hasNoSignedWrap() once SelectionDAG/ISelLowering
4532 // consistently sets them appropriately when making said nodes.
4533
4534 KnownBits KnownSrc = DAG.computeKnownBits(Op.getOperand(1));
4535 return !KnownSrc.getSignedMinValue().isMinSignedValue();
4536}
4537
4539 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
4540 (isIntEqualitySetCC(CC) ||
4541 (isUnsignedIntSetCC(CC) && DAG.isKnownNeverZero(Op.getOperand(1))) ||
4542 (isSignedIntSetCC(CC) && isSafeSignedCMN(Op, DAG)));
4543}
4544
4545/// Returns how profitable it is to fold a comparison's operand's shift and/or
4546/// extension operations into the comparison instruction's second operand
4547/// (so_reg_imm / so_reg_reg for ARM, t2_so_reg for Thumb-2).
4549 // Thumb-1 CMP does not support shifted second operands.
4550 if (ST.isThumb1Only() || !Op.hasOneUse())
4551 return 0;
4552
4553 unsigned Opc = Op.getOpcode();
4554 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA) {
4555 if (auto *ShiftAmt = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
4556 return ShiftAmt->getZExtValue() <= 31 ? 1 : 0;
4557 // Register-controlled shift: only ARM-mode CMP/CMN (so_reg_reg) supports
4558 // this; Thumb-2 t2_so_reg requires an immediate shift amount.
4559 return ST.isThumb() ? 0 : 1;
4560 }
4561
4562 if (Opc == ISD::ROTR) {
4563 // Rotr constants will be normalized via mod 32, or & 31,
4564 // so we do not have to bounds check.
4565 if (isa<ConstantSDNode>(Op.getOperand(1)))
4566 return 1;
4567 return ST.isThumb() ? 0 : 1;
4568 }
4569
4570 return 0;
4571}
4572
4573/// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4574/// the given operands.
4575SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4576 SDValue &ARMcc, SelectionDAG &DAG,
4577 const SDLoc &dl) const {
4578 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4579 unsigned C = RHSC->getZExtValue();
4580 if (!isLegalICmpImmediate((int32_t)C)) {
4581 // Constant does not fit, try adjusting it by one.
4582 switch (CC) {
4583 default: break;
4584 case ISD::SETLT:
4585 case ISD::SETGE:
4586 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4587 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4588 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4589 }
4590 break;
4591 case ISD::SETULT:
4592 case ISD::SETUGE:
4593 if (C != 0 && isLegalICmpImmediate(C-1)) {
4594 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4595 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4596 }
4597 break;
4598 case ISD::SETLE:
4599 case ISD::SETGT:
4600 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4601 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4602 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4603 }
4604 break;
4605 case ISD::SETULE:
4606 case ISD::SETUGT:
4607 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4608 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4609 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4610 }
4611 break;
4612 }
4613 }
4614 }
4615
4616 // Thumb1 has very limited immediate modes, so turning an "and" into a
4617 // shift can save multiple instructions.
4618 //
4619 // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4620 // into "((x << n) >> n)". But that isn't necessarily profitable on its
4621 // own. If it's the operand to an unsigned comparison with an immediate,
4622 // we can eliminate one of the shifts: we transform
4623 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4624 //
4625 // We avoid transforming cases which aren't profitable due to encoding
4626 // details:
4627 //
4628 // 1. C2 fits into the immediate field of a cmp, and the transformed version
4629 // would not; in that case, we're essentially trading one immediate load for
4630 // another.
4631 // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4632 // 3. C2 is zero; we have other code for this special case.
4633 //
4634 // FIXME: Figure out profitability for Thumb2; we usually can't save an
4635 // instruction, since the AND is always one instruction anyway, but we could
4636 // use narrow instructions in some cases.
4637 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4638 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4639 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4640 !isSignedIntSetCC(CC)) {
4641 unsigned Mask = LHS.getConstantOperandVal(1);
4642 auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4643 uint64_t RHSV = RHSC->getZExtValue();
4644 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4645 unsigned ShiftBits = llvm::countl_zero(Mask);
4646 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4647 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4648 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4649 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4650 }
4651 }
4652 }
4653
4654 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4655 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same
4656 // way a cmp would.
4657 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4658 // some tweaks to the heuristics for the previous and->shift transform.
4659 // FIXME: Optimize cases where the LHS isn't a shift.
4660 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4661 isa<ConstantSDNode>(RHS) && RHS->getAsZExtVal() == 0x80000000U &&
4662 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4663 LHS.getConstantOperandVal(1) < 31) {
4664 unsigned ShiftAmt = LHS.getConstantOperandVal(1) + 1;
4665 SDValue Shift =
4666 DAG.getNode(ARMISD::LSLS, dl, DAG.getVTList(MVT::i32, FlagsVT),
4667 LHS.getOperand(0), DAG.getConstant(ShiftAmt, dl, MVT::i32));
4668 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4669 return Shift.getValue(1);
4670 }
4671
4673
4674 unsigned CompareType;
4675 switch (CondCode) {
4676 default:
4677 CompareType = ARMISD::CMP;
4678 break;
4679 case ARMCC::EQ:
4680 case ARMCC::NE:
4681 // Uses only Z Flag
4682 CompareType = ARMISD::CMPZ;
4683 break;
4684 }
4685
4686 // TODO: Remove CMPZ check once we generalize and remove the CMPZ enum from
4687 // the codebase.
4688
4689 // TODO: When we have a solution to the vselect predicate not allowing pl/mi
4690 // all the time, allow those cases to be cmn too no matter what.
4691 if (CompareType != ARMISD::CMPZ && isCMN(RHS, CC, DAG)) {
4692 CompareType = ARMISD::CMN;
4693 RHS = RHS.getOperand(1);
4694 } else if (CompareType != ARMISD::CMPZ && isCMN(LHS, CC, DAG)) {
4695 CompareType = ARMISD::CMN;
4696 LHS = LHS.getOperand(1);
4698 }
4699
4700 // Prefer folding shifts / CMN into the cmp/cmn second operand (so_reg /
4701 // t2_so_reg). When both sides compete, pick the higher
4702 // getCmpOperandFoldingProfit. Only when RHS is not a legal icmp
4703 // immediate: otherwise keep the canonical (reg, imm) form.
4704 ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getNode());
4705 if (!C || !isLegalICmpImmediate(C->getSExtValue())) {
4706 if (getCmpOperandFoldingProfit(LHS, *Subtarget) >
4707 getCmpOperandFoldingProfit(RHS, *Subtarget)) {
4708 std::swap(LHS, RHS);
4709 if (CompareType == ARMISD::CMP)
4711 }
4712 }
4713
4714 // If the RHS is a constant zero then the V (overflow) flag will never be
4715 // set. This can allow us to simplify GE to PL or LT to MI, which can be
4716 // simpler for other passes (like the peephole optimiser) to deal with.
4717 if (isNullConstant(RHS)) {
4718 switch (CondCode) {
4719 default:
4720 break;
4721 case ARMCC::GE:
4723 break;
4724 case ARMCC::LT:
4726 break;
4727 }
4728 }
4729
4730 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4731 return DAG.getNode(CompareType, dl, FlagsVT, LHS, RHS);
4732}
4733
4734/// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4735SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4736 SelectionDAG &DAG, const SDLoc &dl,
4737 bool Signaling) const {
4738 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4739 SDValue Flags;
4741 Flags = DAG.getNode(Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP, dl, FlagsVT,
4742 LHS, RHS);
4743 else
4744 Flags = DAG.getNode(Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0, dl,
4745 FlagsVT, LHS);
4746 return DAG.getNode(ARMISD::FMSTAT, dl, FlagsVT, Flags);
4747}
4748
4749// This function returns three things: the arithmetic computation itself
4750// (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The
4751// comparison and the condition code define the case in which the arithmetic
4752// computation *does not* overflow.
4753std::pair<SDValue, SDValue>
4754ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4755 SDValue &ARMcc) const {
4756 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
4757
4758 SDValue Value, OverflowCmp;
4759 SDValue LHS = Op.getOperand(0);
4760 SDValue RHS = Op.getOperand(1);
4761 SDLoc dl(Op);
4762
4763 // FIXME: We are currently always generating CMPs because we don't support
4764 // generating CMN through the backend. This is not as good as the natural
4765 // CMP case because it causes a register dependency and cannot be folded
4766 // later.
4767
4768 switch (Op.getOpcode()) {
4769 default:
4770 llvm_unreachable("Unknown overflow instruction!");
4771 case ISD::SADDO:
4772 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4773 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4774 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, FlagsVT, Value, LHS);
4775 break;
4776 case ISD::UADDO:
4777 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4778 // We use ADDC here to correspond to its use in LowerALUO.
4779 // We do not use it in the USUBO case as Value may not be used.
4780 Value = DAG.getNode(ARMISD::ADDC, dl,
4781 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4782 .getValue(0);
4783 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, FlagsVT, Value, LHS);
4784 break;
4785 case ISD::SSUBO:
4786 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4787 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4788 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, FlagsVT, LHS, RHS);
4789 break;
4790 case ISD::USUBO:
4791 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4792 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4793 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, FlagsVT, LHS, RHS);
4794 break;
4795 case ISD::UMULO:
4796 // We generate a UMUL_LOHI and then check if the high word is 0.
4797 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4798 Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4799 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4800 LHS, RHS);
4801 OverflowCmp = DAG.getNode(ARMISD::CMPZ, dl, FlagsVT, Value.getValue(1),
4802 DAG.getConstant(0, dl, MVT::i32));
4803 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4804 break;
4805 case ISD::SMULO:
4806 // We generate a SMUL_LOHI and then check if all the bits of the high word
4807 // are the same as the sign bit of the low word.
4808 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4809 Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4810 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4811 LHS, RHS);
4812 OverflowCmp = DAG.getNode(ARMISD::CMPZ, dl, FlagsVT, Value.getValue(1),
4813 DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4814 Value.getValue(0),
4815 DAG.getConstant(31, dl, MVT::i32)));
4816 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4817 break;
4818 } // switch (...)
4819
4820 return std::make_pair(Value, OverflowCmp);
4821}
4822
4824 SDLoc DL(Value);
4825 EVT VT = Value.getValueType();
4826
4827 if (Invert)
4828 Value = DAG.getNode(ISD::SUB, DL, MVT::i32,
4829 DAG.getConstant(1, DL, MVT::i32), Value);
4830
4831 SDValue Cmp = DAG.getNode(ARMISD::SUBC, DL, DAG.getVTList(VT, MVT::i32),
4832 Value, DAG.getConstant(1, DL, VT));
4833 return Cmp.getValue(1);
4834}
4835
4837 bool Invert) {
4838 SDLoc DL(Flags);
4839
4840 if (Invert) {
4841 // Convert flags to boolean with ADDE 0,0,Carry then compute 1 - bool.
4842 SDValue BoolCarry = DAG.getNode(
4843 ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4844 DAG.getConstant(0, DL, VT), DAG.getConstant(0, DL, VT), Flags);
4845 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(1, DL, VT), BoolCarry);
4846 }
4847
4848 // Now convert the carry flag into a boolean carry. We do this
4849 // using ARMISD::ADDE 0, 0, Carry
4850 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4851 DAG.getConstant(0, DL, VT), DAG.getConstant(0, DL, VT),
4852 Flags);
4853}
4854
4855// Value is 1 if 'V' bit is 1, else 0
4857 SDLoc DL(Flags);
4858 SDValue Zero = DAG.getConstant(0, DL, VT);
4859 SDValue One = DAG.getConstant(1, DL, VT);
4860 SDValue ARMcc = DAG.getConstant(ARMCC::VS, DL, MVT::i32);
4861 return DAG.getNode(ARMISD::CMOV, DL, VT, Zero, One, ARMcc, Flags);
4862}
4863
4864SDValue ARMTargetLowering::LowerALUO(SDValue Op, SelectionDAG &DAG) const {
4865 // Let legalize expand this if it isn't a legal type yet.
4866 if (!isTypeLegal(Op.getValueType()))
4867 return SDValue();
4868
4869 SDValue LHS = Op.getOperand(0);
4870 SDValue RHS = Op.getOperand(1);
4871 SDLoc dl(Op);
4872
4873 EVT VT = Op.getValueType();
4874 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4875 SDValue Value;
4876 SDValue Overflow;
4877 switch (Op.getOpcode()) {
4878 case ISD::UADDO:
4879 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4880 // Convert the carry flag into a boolean value.
4881 Overflow = carryFlagToValue(Value.getValue(1), VT, DAG, false);
4882 break;
4883 case ISD::USUBO:
4884 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4885 // Convert the carry flag into a boolean value.
4886 Overflow = carryFlagToValue(Value.getValue(1), VT, DAG, true);
4887 break;
4888 default: {
4889 // Handle other operations with getARMXALUOOp
4890 SDValue OverflowCmp, ARMcc;
4891 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4892 // We use 0 and 1 as false and true values.
4893 // ARMcc represents the "no overflow" condition (e.g., VC for signed ops).
4894 // CMOV operand order is (FalseVal, TrueVal), so we put 1 in FalseVal
4895 // position to get Overflow=1 when the "no overflow" condition is false.
4896 Overflow =
4897 DAG.getNode(ARMISD::CMOV, dl, MVT::i32,
4898 DAG.getConstant(1, dl, MVT::i32), // FalseVal: overflow
4899 DAG.getConstant(0, dl, MVT::i32), // TrueVal: no overflow
4900 ARMcc, OverflowCmp);
4901 break;
4902 }
4903 }
4904
4905 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4906}
4907
4909 const ARMSubtarget *Subtarget) {
4910 EVT VT = Op.getValueType();
4911 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP() || Subtarget->isThumb1Only())
4912 return SDValue();
4913 if (!VT.isSimple())
4914 return SDValue();
4915
4916 unsigned NewOpcode;
4917 switch (VT.getSimpleVT().SimpleTy) {
4918 default:
4919 return SDValue();
4920 case MVT::i8:
4921 switch (Op->getOpcode()) {
4922 case ISD::UADDSAT:
4923 NewOpcode = ARMISD::UQADD8b;
4924 break;
4925 case ISD::SADDSAT:
4926 NewOpcode = ARMISD::QADD8b;
4927 break;
4928 case ISD::USUBSAT:
4929 NewOpcode = ARMISD::UQSUB8b;
4930 break;
4931 case ISD::SSUBSAT:
4932 NewOpcode = ARMISD::QSUB8b;
4933 break;
4934 }
4935 break;
4936 case MVT::i16:
4937 switch (Op->getOpcode()) {
4938 case ISD::UADDSAT:
4939 NewOpcode = ARMISD::UQADD16b;
4940 break;
4941 case ISD::SADDSAT:
4942 NewOpcode = ARMISD::QADD16b;
4943 break;
4944 case ISD::USUBSAT:
4945 NewOpcode = ARMISD::UQSUB16b;
4946 break;
4947 case ISD::SSUBSAT:
4948 NewOpcode = ARMISD::QSUB16b;
4949 break;
4950 }
4951 break;
4952 }
4953
4954 SDLoc dl(Op);
4955 SDValue Add =
4956 DAG.getNode(NewOpcode, dl, MVT::i32,
4957 DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32),
4958 DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32));
4959 return DAG.getNode(ISD::TRUNCATE, dl, VT, Add);
4960}
4961
4962SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4963 SDValue Cond = Op.getOperand(0);
4964 SDValue SelectTrue = Op.getOperand(1);
4965 SDValue SelectFalse = Op.getOperand(2);
4966 SDLoc dl(Op);
4967 unsigned Opc = Cond.getOpcode();
4968
4969 if (Cond.getResNo() == 1 &&
4970 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4971 Opc == ISD::USUBO)) {
4972 if (!isTypeLegal(Cond->getValueType(0)))
4973 return SDValue();
4974
4975 SDValue Value, OverflowCmp;
4976 SDValue ARMcc;
4977 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4978 EVT VT = Op.getValueType();
4979
4980 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, OverflowCmp, DAG);
4981 }
4982
4983 // Convert:
4984 //
4985 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4986 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4987 //
4988 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4989 const ConstantSDNode *CMOVTrue =
4990 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4991 const ConstantSDNode *CMOVFalse =
4992 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4993
4994 if (CMOVTrue && CMOVFalse) {
4995 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4996 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4997
4998 SDValue True;
4999 SDValue False;
5000 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
5001 True = SelectTrue;
5002 False = SelectFalse;
5003 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
5004 True = SelectFalse;
5005 False = SelectTrue;
5006 }
5007
5008 if (True.getNode() && False.getNode())
5009 return getCMOV(dl, Op.getValueType(), True, False, Cond.getOperand(2),
5010 Cond.getOperand(3), DAG);
5011 }
5012 }
5013
5014 return DAG.getSelectCC(dl, Cond,
5015 DAG.getConstant(0, dl, Cond.getValueType()),
5016 SelectTrue, SelectFalse, ISD::SETNE);
5017}
5018
5020 bool &swpCmpOps, bool &swpVselOps) {
5021 // Start by selecting the GE condition code for opcodes that return true for
5022 // 'equality'
5023 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
5024 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE)
5025 CondCode = ARMCC::GE;
5026
5027 // and GT for opcodes that return false for 'equality'.
5028 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
5029 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT)
5030 CondCode = ARMCC::GT;
5031
5032 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
5033 // to swap the compare operands.
5034 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
5035 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT)
5036 swpCmpOps = true;
5037
5038 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
5039 // If we have an unordered opcode, we need to swap the operands to the VSEL
5040 // instruction (effectively negating the condition).
5041 //
5042 // This also has the effect of swapping which one of 'less' or 'greater'
5043 // returns true, so we also swap the compare operands. It also switches
5044 // whether we return true for 'equality', so we compensate by picking the
5045 // opposite condition code to our original choice.
5046 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
5047 CC == ISD::SETUGT) {
5048 swpCmpOps = !swpCmpOps;
5049 swpVselOps = !swpVselOps;
5050 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
5051 }
5052
5053 // 'ordered' is 'anything but unordered', so use the VS condition code and
5054 // swap the VSEL operands.
5055 if (CC == ISD::SETO) {
5056 CondCode = ARMCC::VS;
5057 swpVselOps = true;
5058 }
5059
5060 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
5061 // code and swap the VSEL operands. Also do this if we don't care about the
5062 // unordered case.
5063 if (CC == ISD::SETUNE || CC == ISD::SETNE) {
5064 CondCode = ARMCC::EQ;
5065 swpVselOps = true;
5066 }
5067}
5068
5069SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
5070 SDValue TrueVal, SDValue ARMcc,
5071 SDValue Flags, SelectionDAG &DAG) const {
5072 if (!Subtarget->hasFP64() && VT == MVT::f64) {
5073 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
5074 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
5075 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
5076 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
5077
5078 SDValue TrueLow = TrueVal.getValue(0);
5079 SDValue TrueHigh = TrueVal.getValue(1);
5080 SDValue FalseLow = FalseVal.getValue(0);
5081 SDValue FalseHigh = FalseVal.getValue(1);
5082
5083 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
5084 ARMcc, Flags);
5085 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
5086 ARMcc, Flags);
5087
5088 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
5089 }
5090 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, Flags);
5091}
5092
5093static bool isGTorGE(ISD::CondCode CC) {
5094 return CC == ISD::SETGT || CC == ISD::SETGE;
5095}
5096
5097static bool isLTorLE(ISD::CondCode CC) {
5098 return CC == ISD::SETLT || CC == ISD::SETLE;
5099}
5100
5101// See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
5102// All of these conditions (and their <= and >= counterparts) will do:
5103// x < k ? k : x
5104// x > k ? x : k
5105// k < x ? x : k
5106// k > x ? k : x
5107static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
5108 const SDValue TrueVal, const SDValue FalseVal,
5109 const ISD::CondCode CC, const SDValue K) {
5110 return (isGTorGE(CC) &&
5111 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
5112 (isLTorLE(CC) &&
5113 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
5114}
5115
5116// Check if two chained conditionals could be converted into SSAT or USAT.
5117//
5118// SSAT can replace a set of two conditional selectors that bound a number to an
5119// interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
5120//
5121// x < -k ? -k : (x > k ? k : x)
5122// x < -k ? -k : (x < k ? x : k)
5123// x > -k ? (x > k ? k : x) : -k
5124// x < k ? (x < -k ? -k : x) : k
5125// etc.
5126//
5127// LLVM canonicalizes these to either a min(max()) or a max(min())
5128// pattern. This function tries to match one of these and will return a SSAT
5129// node if successful.
5130//
5131// USAT works similarly to SSAT but bounds on the interval [0, k] where k + 1
5132// is a power of 2.
5134 EVT VT = Op.getValueType();
5135 SDValue V1 = Op.getOperand(0);
5136 SDValue K1 = Op.getOperand(1);
5137 SDValue TrueVal1 = Op.getOperand(2);
5138 SDValue FalseVal1 = Op.getOperand(3);
5139 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5140
5141 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
5142 if (Op2.getOpcode() != ISD::SELECT_CC)
5143 return SDValue();
5144
5145 SDValue V2 = Op2.getOperand(0);
5146 SDValue K2 = Op2.getOperand(1);
5147 SDValue TrueVal2 = Op2.getOperand(2);
5148 SDValue FalseVal2 = Op2.getOperand(3);
5149 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
5150
5151 SDValue V1Tmp = V1;
5152 SDValue V2Tmp = V2;
5153
5154 // Check that the registers and the constants match a max(min()) or min(max())
5155 // pattern
5156 if (V1Tmp != TrueVal1 || V2Tmp != TrueVal2 || K1 != FalseVal1 ||
5157 K2 != FalseVal2 ||
5158 !((isGTorGE(CC1) && isLTorLE(CC2)) || (isLTorLE(CC1) && isGTorGE(CC2))))
5159 return SDValue();
5160
5161 // Check that the constant in the lower-bound check is
5162 // the opposite of the constant in the upper-bound check
5163 // in 1's complement.
5165 return SDValue();
5166
5167 int64_t Val1 = cast<ConstantSDNode>(K1)->getSExtValue();
5168 int64_t Val2 = cast<ConstantSDNode>(K2)->getSExtValue();
5169 int64_t PosVal = std::max(Val1, Val2);
5170 int64_t NegVal = std::min(Val1, Val2);
5171
5172 if (!((Val1 > Val2 && isLTorLE(CC1)) || (Val1 < Val2 && isLTorLE(CC2))) ||
5173 !isPowerOf2_64(PosVal + 1))
5174 return SDValue();
5175
5176 // Handle the difference between USAT (unsigned) and SSAT (signed)
5177 // saturation
5178 // At this point, PosVal is guaranteed to be positive
5179 uint64_t K = PosVal;
5180 SDLoc dl(Op);
5181 if (Val1 == ~Val2)
5182 return DAG.getNode(ARMISD::SSAT, dl, VT, V2Tmp,
5183 DAG.getConstant(llvm::countr_one(K), dl, VT));
5184 if (NegVal == 0)
5185 return DAG.getNode(ARMISD::USAT, dl, VT, V2Tmp,
5186 DAG.getConstant(llvm::countr_one(K), dl, VT));
5187
5188 return SDValue();
5189}
5190
5191// Check if a condition of the type x < k ? k : x can be converted into a
5192// bit operation instead of conditional moves.
5193// Currently this is allowed given:
5194// - The conditions and values match up
5195// - k is 0 or -1 (all ones)
5196// This function will not check the last condition, thats up to the caller
5197// It returns true if the transformation can be made, and in such case
5198// returns x in V, and k in SatK.
5200 SDValue &SatK)
5201{
5202 SDValue LHS = Op.getOperand(0);
5203 SDValue RHS = Op.getOperand(1);
5204 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5205 SDValue TrueVal = Op.getOperand(2);
5206 SDValue FalseVal = Op.getOperand(3);
5207
5209 ? &RHS
5210 : nullptr;
5211
5212 // No constant operation in comparison, early out
5213 if (!K)
5214 return false;
5215
5216 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
5217 V = (KTmp == TrueVal) ? FalseVal : TrueVal;
5218 SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
5219
5220 // If the constant on left and right side, or variable on left and right,
5221 // does not match, early out
5222 if (*K != KTmp || V != VTmp)
5223 return false;
5224
5225 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
5226 SatK = *K;
5227 return true;
5228 }
5229
5230 return false;
5231}
5232
5233bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
5234 if (VT == MVT::f32)
5235 return !Subtarget->hasVFP2Base();
5236 if (VT == MVT::f64)
5237 return !Subtarget->hasFP64();
5238 if (VT == MVT::f16)
5239 return !Subtarget->hasFullFP16();
5240 return false;
5241}
5242
5243static SDValue matchCSET(unsigned &Opcode, bool &InvertCond, SDValue TrueVal,
5244 SDValue FalseVal, const ARMSubtarget *Subtarget) {
5245 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
5246 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
5247 if (!CFVal || !CTVal || !Subtarget->hasV8_1MMainlineOps())
5248 return SDValue();
5249
5250 unsigned TVal = CTVal->getZExtValue();
5251 unsigned FVal = CFVal->getZExtValue();
5252
5253 Opcode = 0;
5254 InvertCond = false;
5255 if (TVal == ~FVal) {
5256 Opcode = ARMISD::CSINV;
5257 } else if (TVal == ~FVal + 1) {
5258 Opcode = ARMISD::CSNEG;
5259 } else if (TVal + 1 == FVal) {
5260 Opcode = ARMISD::CSINC;
5261 } else if (TVal == FVal + 1) {
5262 Opcode = ARMISD::CSINC;
5263 std::swap(TrueVal, FalseVal);
5264 std::swap(TVal, FVal);
5265 InvertCond = !InvertCond;
5266 } else {
5267 return SDValue();
5268 }
5269
5270 // If one of the constants is cheaper than another, materialise the
5271 // cheaper one and let the csel generate the other.
5272 if (Opcode != ARMISD::CSINC &&
5273 HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) {
5274 std::swap(TrueVal, FalseVal);
5275 std::swap(TVal, FVal);
5276 InvertCond = !InvertCond;
5277 }
5278
5279 // Attempt to use ZR checking TVal is 0, possibly inverting the condition
5280 // to get there. CSINC not is invertable like the other two (~(~a) == a,
5281 // -(-a) == a, but (a+1)+1 != a).
5282 if (FVal == 0 && Opcode != ARMISD::CSINC) {
5283 std::swap(TrueVal, FalseVal);
5284 std::swap(TVal, FVal);
5285 InvertCond = !InvertCond;
5286 }
5287
5288 return TrueVal;
5289}
5290
5291SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5292 EVT VT = Op.getValueType();
5293 SDLoc dl(Op);
5294
5295 // Try to convert two saturating conditional selects into a single SSAT
5296 if ((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2())
5297 if (SDValue SatValue = LowerSaturatingConditional(Op, DAG))
5298 return SatValue;
5299
5300 // Try to convert expressions of the form x < k ? k : x (and similar forms)
5301 // into more efficient bit operations, which is possible when k is 0 or -1
5302 // On ARM and Thumb-2 which have flexible operand 2 this will result in
5303 // single instructions. On Thumb the shift and the bit operation will be two
5304 // instructions.
5305 // Only allow this transformation on full-width (32-bit) operations
5306 SDValue LowerSatConstant;
5307 SDValue SatValue;
5308 if (VT == MVT::i32 &&
5309 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
5310 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
5311 DAG.getConstant(31, dl, VT));
5312 if (isNullConstant(LowerSatConstant)) {
5313 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
5314 DAG.getAllOnesConstant(dl, VT));
5315 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
5316 } else if (isAllOnesConstant(LowerSatConstant))
5317 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
5318 }
5319
5320 SDValue LHS = Op.getOperand(0);
5321 SDValue RHS = Op.getOperand(1);
5322 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5323 SDValue TrueVal = Op.getOperand(2);
5324 SDValue FalseVal = Op.getOperand(3);
5325 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
5326 ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
5327 if (Op.getValueType().isInteger()) {
5328
5329 // Check for SMAX(lhs, 0) and SMIN(lhs, 0) patterns.
5330 // (SELECT_CC setgt, lhs, 0, lhs, 0) -> (BIC lhs, (SRA lhs, typesize-1))
5331 // (SELECT_CC setlt, lhs, 0, lhs, 0) -> (AND lhs, (SRA lhs, typesize-1))
5332 // Both require less instructions than compare and conditional select.
5333 if ((CC == ISD::SETGT || CC == ISD::SETLT) && LHS == TrueVal && RHSC &&
5334 RHSC->isZero() && CFVal && CFVal->isZero() &&
5335 LHS.getValueType() == RHS.getValueType()) {
5336 EVT VT = LHS.getValueType();
5337 SDValue Shift =
5338 DAG.getNode(ISD::SRA, dl, VT, LHS,
5339 DAG.getConstant(VT.getSizeInBits() - 1, dl, VT));
5340
5341 if (CC == ISD::SETGT)
5342 Shift = DAG.getNOT(dl, Shift, VT);
5343
5344 return DAG.getNode(ISD::AND, dl, VT, LHS, Shift);
5345 }
5346
5347 // (SELECT_CC setlt, x, 0, 1, 0) -> SRL(x, bw-1)
5348 if (CC == ISD::SETLT && isNullConstant(RHS) && isOneConstant(TrueVal) &&
5349 isNullConstant(FalseVal) && LHS.getValueType() == VT)
5350 return DAG.getNode(ISD::SRL, dl, VT, LHS,
5351 DAG.getConstant(VT.getSizeInBits() - 1, dl, VT));
5352 }
5353
5354 if (LHS.getValueType() == MVT::i32) {
5355 unsigned Opcode;
5356 bool InvertCond;
5357 if (SDValue Op =
5358 matchCSET(Opcode, InvertCond, TrueVal, FalseVal, Subtarget)) {
5359 if (InvertCond)
5360 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5361
5362 SDValue ARMcc;
5363 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5364 EVT VT = Op.getValueType();
5365 return DAG.getNode(Opcode, dl, VT, Op, Op, ARMcc, Cmp);
5366 }
5367 }
5368
5369 if (isUnsupportedFloatingType(LHS.getValueType())) {
5370 softenSetCCOperands(DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5371
5372 // If softenSetCCOperands only returned one value, we should compare it to
5373 // zero.
5374 if (!RHS.getNode()) {
5375 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5376 CC = ISD::SETNE;
5377 }
5378 }
5379
5380 if (LHS.getValueType() == MVT::i32) {
5381 // Try to generate VSEL on ARMv8.
5382 // The VSEL instruction can't use all the usual ARM condition
5383 // codes: it only has two bits to select the condition code, so it's
5384 // constrained to use only GE, GT, VS and EQ.
5385 //
5386 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
5387 // swap the operands of the previous compare instruction (effectively
5388 // inverting the compare condition, swapping 'less' and 'greater') and
5389 // sometimes need to swap the operands to the VSEL (which inverts the
5390 // condition in the sense of firing whenever the previous condition didn't)
5391 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
5392 TrueVal.getValueType() == MVT::f32 ||
5393 TrueVal.getValueType() == MVT::f64)) {
5395 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
5396 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
5397 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5398 std::swap(TrueVal, FalseVal);
5399 }
5400 }
5401
5402 SDValue ARMcc;
5403 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5404 // Choose GE over PL, which vsel does now support
5405 if (ARMcc->getAsZExtVal() == ARMCC::PL)
5406 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
5407 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, Cmp, DAG);
5408 }
5409
5410 ARMCC::CondCodes CondCode, CondCode2;
5411 FPCCToARMCC(CC, CondCode, CondCode2);
5412
5413 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
5414 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
5415 // must use VSEL (limited condition codes), due to not having conditional f16
5416 // moves.
5417 if (Subtarget->hasFPARMv8Base() &&
5418 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
5419 (TrueVal.getValueType() == MVT::f16 ||
5420 TrueVal.getValueType() == MVT::f32 ||
5421 TrueVal.getValueType() == MVT::f64)) {
5422 bool swpCmpOps = false;
5423 bool swpVselOps = false;
5424 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
5425
5426 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
5427 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
5428 if (swpCmpOps)
5429 std::swap(LHS, RHS);
5430 if (swpVselOps)
5431 std::swap(TrueVal, FalseVal);
5432 }
5433 }
5434
5435 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5436 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5437 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, Cmp, DAG);
5438 if (CondCode2 != ARMCC::AL) {
5439 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
5440 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, Cmp, DAG);
5441 }
5442 return Result;
5443}
5444
5445/// canChangeToInt - Given the fp compare operand, return true if it is suitable
5446/// to morph to an integer compare sequence.
5447static bool canChangeToInt(SDValue Op, bool &SeenZero,
5448 const ARMSubtarget *Subtarget) {
5449 SDNode *N = Op.getNode();
5450 if (!N->hasOneUse())
5451 // Otherwise it requires moving the value from fp to integer registers.
5452 return false;
5453 if (!N->getNumValues())
5454 return false;
5455 EVT VT = Op.getValueType();
5456 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
5457 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
5458 // vmrs are very slow, e.g. cortex-a8.
5459 return false;
5460
5461 if (isFloatingPointZero(Op)) {
5462 SeenZero = true;
5463 return true;
5464 }
5465 return ISD::isNormalLoad(N);
5466}
5467
5470 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
5471
5473 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
5474 Ld->getPointerInfo(), Ld->getAlign(),
5475 Ld->getMemOperand()->getFlags());
5476
5477 llvm_unreachable("Unknown VFP cmp argument!");
5478}
5479
5481 SDValue &RetVal1, SDValue &RetVal2) {
5482 SDLoc dl(Op);
5483
5484 if (isFloatingPointZero(Op)) {
5485 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
5486 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
5487 return;
5488 }
5489
5490 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5491 SDValue Ptr = Ld->getBasePtr();
5492 RetVal1 =
5493 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5494 Ld->getAlign(), Ld->getMemOperand()->getFlags());
5495
5496 EVT PtrType = Ptr.getValueType();
5497 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5498 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5499 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5500 Ld->getPointerInfo().getWithOffset(4),
5501 commonAlignment(Ld->getAlign(), 4),
5502 Ld->getMemOperand()->getFlags());
5503 return;
5504 }
5505
5506 llvm_unreachable("Unknown VFP cmp argument!");
5507}
5508
5509/// OptimizeVFPBrcond - With nnan and without daz, it's legal to optimize some
5510/// f32 and even f64 comparisons to integer ones.
5511SDValue
5512ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5513 SDValue Chain = Op.getOperand(0);
5514 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5515 SDValue LHS = Op.getOperand(2);
5516 SDValue RHS = Op.getOperand(3);
5517 SDValue Dest = Op.getOperand(4);
5518 SDLoc dl(Op);
5519
5520 bool LHSSeenZero = false;
5521 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5522 bool RHSSeenZero = false;
5523 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5524 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5525 // If unsafe fp math optimization is enabled and there are no other uses of
5526 // the CMP operands, and the condition code is EQ or NE, we can optimize it
5527 // to an integer comparison.
5528 if (CC == ISD::SETOEQ)
5529 CC = ISD::SETEQ;
5530 else if (CC == ISD::SETUNE)
5531 CC = ISD::SETNE;
5532
5533 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5534 SDValue ARMcc;
5535 if (LHS.getValueType() == MVT::f32) {
5536 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5537 bitcastf32Toi32(LHS, DAG), Mask);
5538 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5539 bitcastf32Toi32(RHS, DAG), Mask);
5540 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5541 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc,
5542 Cmp);
5543 }
5544
5545 SDValue LHS1, LHS2;
5546 SDValue RHS1, RHS2;
5547 expandf64Toi32(LHS, DAG, LHS1, LHS2);
5548 expandf64Toi32(RHS, DAG, RHS1, RHS2);
5549 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5550 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5552 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5553 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5554 return DAG.getNode(ARMISD::BCC_i64, dl, MVT::Other, Ops);
5555 }
5556
5557 return SDValue();
5558}
5559
5560// Generate CMP + CMOV for integer abs.
5561SDValue ARMTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
5562 SDLoc DL(Op);
5563
5564 SDValue Neg = DAG.getNegative(Op.getOperand(0), DL, MVT::i32);
5565
5566 // Generate CMP & CMOV.
5567 SDValue Cmp = DAG.getNode(ARMISD::CMP, DL, FlagsVT, Op.getOperand(0),
5568 DAG.getConstant(0, DL, MVT::i32));
5569 return DAG.getNode(ARMISD::CMOV, DL, MVT::i32, Op.getOperand(0), Neg,
5570 DAG.getConstant(ARMCC::MI, DL, MVT::i32), Cmp);
5571}
5572
5574 ARMCC::CondCodes CondCode =
5575 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
5576 CondCode = ARMCC::getOppositeCondition(CondCode);
5577 return DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5578}
5579
5580SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5581 SDValue Chain = Op.getOperand(0);
5582 SDValue Cond = Op.getOperand(1);
5583 SDValue Dest = Op.getOperand(2);
5584 SDLoc dl(Op);
5585
5586 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5587 // instruction.
5588 unsigned Opc = Cond.getOpcode();
5589 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5590 !Subtarget->isThumb1Only();
5591 if (Cond.getResNo() == 1 &&
5592 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5593 Opc == ISD::USUBO || OptimizeMul)) {
5594 // Only lower legal XALUO ops.
5595 if (!isTypeLegal(Cond->getValueType(0)))
5596 return SDValue();
5597
5598 // The actual operation with overflow check.
5599 SDValue Value, OverflowCmp;
5600 SDValue ARMcc;
5601 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5602
5603 // Reverse the condition code.
5604 ARMcc = getInvertedARMCondCode(ARMcc, DAG);
5605
5606 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc,
5607 OverflowCmp);
5608 }
5609
5610 return SDValue();
5611}
5612
5613SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5614 SDValue Chain = Op.getOperand(0);
5615 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5616 SDValue LHS = Op.getOperand(2);
5617 SDValue RHS = Op.getOperand(3);
5618 SDValue Dest = Op.getOperand(4);
5619 SDLoc dl(Op);
5620
5621 if (isUnsupportedFloatingType(LHS.getValueType())) {
5622 softenSetCCOperands(DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5623
5624 // If softenSetCCOperands only returned one value, we should compare it to
5625 // zero.
5626 if (!RHS.getNode()) {
5627 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5628 CC = ISD::SETNE;
5629 }
5630 }
5631
5632 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5633 // instruction.
5634 unsigned Opc = LHS.getOpcode();
5635 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5636 !Subtarget->isThumb1Only();
5637 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5638 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5639 Opc == ISD::USUBO || OptimizeMul) &&
5640 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5641 // Only lower legal XALUO ops.
5642 if (!isTypeLegal(LHS->getValueType(0)))
5643 return SDValue();
5644
5645 // The actual operation with overflow check.
5646 SDValue Value, OverflowCmp;
5647 SDValue ARMcc;
5648 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5649
5650 if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5651 // Reverse the condition code.
5652 ARMcc = getInvertedARMCondCode(ARMcc, DAG);
5653 }
5654
5655 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc,
5656 OverflowCmp);
5657 }
5658
5659 if (LHS.getValueType() == MVT::i32) {
5660 SDValue ARMcc;
5661 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5662 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, Cmp);
5663 }
5664
5665 SDNodeFlags Flags = Op->getFlags();
5666 if (Flags.hasNoNaNs() &&
5667 DAG.getDenormalMode(MVT::f32) == DenormalMode::getIEEE() &&
5668 DAG.getDenormalMode(MVT::f64) == DenormalMode::getIEEE() &&
5669 (CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETNE ||
5670 CC == ISD::SETUNE)) {
5671 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5672 return Result;
5673 }
5674
5675 ARMCC::CondCodes CondCode, CondCode2;
5676 FPCCToARMCC(CC, CondCode, CondCode2);
5677
5678 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5679 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5680 SDValue Ops[] = {Chain, Dest, ARMcc, Cmp};
5681 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Ops);
5682 if (CondCode2 != ARMCC::AL) {
5683 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5684 SDValue Ops[] = {Res, Dest, ARMcc, Cmp};
5685 Res = DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Ops);
5686 }
5687 return Res;
5688}
5689
5690SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5691 SDValue Chain = Op.getOperand(0);
5692 SDValue Table = Op.getOperand(1);
5693 SDValue Index = Op.getOperand(2);
5694 SDLoc dl(Op);
5695
5696 EVT PTy = getPointerTy(DAG.getDataLayout());
5697 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5698 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5699 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5700 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5701 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5702 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5703 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5704 // which does another jump to the destination. This also makes it easier
5705 // to translate it to TBB / TBH later (Thumb2 only).
5706 // FIXME: This might not work if the function is extremely large.
5707 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5708 Addr, Op.getOperand(2), JTI);
5709 }
5710 if (isPositionIndependent() || Subtarget->isROPI()) {
5711 Addr =
5712 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5714 Chain = Addr.getValue(1);
5715 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5716 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5717 } else {
5718 Addr =
5719 DAG.getLoad(PTy, dl, Chain, Addr,
5721 Chain = Addr.getValue(1);
5722 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5723 }
5724}
5725
5727 EVT VT = Op.getValueType();
5728 SDLoc dl(Op);
5729
5730 if (Op.getValueType().getVectorElementType() == MVT::i32) {
5731 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5732 return Op;
5733 return DAG.UnrollVectorOp(Op.getNode());
5734 }
5735
5736 const bool HasFullFP16 = DAG.getSubtarget<ARMSubtarget>().hasFullFP16();
5737
5738 EVT NewTy;
5739 const EVT OpTy = Op.getOperand(0).getValueType();
5740 if (OpTy == MVT::v4f32)
5741 NewTy = MVT::v4i32;
5742 else if (OpTy == MVT::v4f16 && HasFullFP16)
5743 NewTy = MVT::v4i16;
5744 else if (OpTy == MVT::v8f16 && HasFullFP16)
5745 NewTy = MVT::v8i16;
5746 else
5747 llvm_unreachable("Invalid type for custom lowering!");
5748
5749 if (VT != MVT::v4i16 && VT != MVT::v8i16)
5750 return DAG.UnrollVectorOp(Op.getNode());
5751
5752 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5753 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5754}
5755
5756SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5757 EVT VT = Op.getValueType();
5758 if (VT.isVector())
5759 return LowerVectorFP_TO_INT(Op, DAG);
5760
5761 bool IsStrict = Op->isStrictFPOpcode();
5762 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
5763
5764 if (isUnsupportedFloatingType(SrcVal.getValueType())) {
5765 RTLIB::Libcall LC;
5766 if (Op.getOpcode() == ISD::FP_TO_SINT ||
5767 Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
5768 LC = RTLIB::getFPTOSINT(SrcVal.getValueType(),
5769 Op.getValueType());
5770 else
5771 LC = RTLIB::getFPTOUINT(SrcVal.getValueType(),
5772 Op.getValueType());
5773 SDLoc Loc(Op);
5774 MakeLibCallOptions CallOptions;
5775 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
5777 std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
5778 CallOptions, Loc, Chain);
5779 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
5780 }
5781
5782 return Op;
5783}
5784
5786 const ARMSubtarget *Subtarget) {
5787 EVT VT = Op.getValueType();
5788 EVT ToVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
5789 EVT FromVT = Op.getOperand(0).getValueType();
5790
5791 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f32)
5792 return Op;
5793 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f64 &&
5794 Subtarget->hasFP64())
5795 return Op;
5796 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f16 &&
5797 Subtarget->hasFullFP16())
5798 return Op;
5799 if (VT == MVT::v4i32 && ToVT == MVT::i32 && FromVT == MVT::v4f32 &&
5800 Subtarget->hasMVEFloatOps())
5801 return Op;
5802 if (VT == MVT::v8i16 && ToVT == MVT::i16 && FromVT == MVT::v8f16 &&
5803 Subtarget->hasMVEFloatOps())
5804 return Op;
5805
5806 if (FromVT != MVT::v4f32 && FromVT != MVT::v8f16)
5807 return SDValue();
5808
5809 SDLoc DL(Op);
5810 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
5811 unsigned BW = ToVT.getScalarSizeInBits() - IsSigned;
5812 SDValue CVT = DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
5813 DAG.getValueType(VT.getScalarType()));
5814 SDValue Max = DAG.getNode(IsSigned ? ISD::SMIN : ISD::UMIN, DL, VT, CVT,
5815 DAG.getConstant((1 << BW) - 1, DL, VT));
5816 if (IsSigned)
5817 Max = DAG.getNode(ISD::SMAX, DL, VT, Max,
5818 DAG.getSignedConstant(-(1 << BW), DL, VT));
5819 return Max;
5820}
5821
5823 EVT VT = Op.getValueType();
5824 SDLoc dl(Op);
5825
5826 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5827 if (VT.getVectorElementType() == MVT::f32)
5828 return Op;
5829 return DAG.UnrollVectorOp(Op.getNode());
5830 }
5831
5832 assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5833 Op.getOperand(0).getValueType() == MVT::v8i16) &&
5834 "Invalid type for custom lowering!");
5835
5836 const bool HasFullFP16 = DAG.getSubtarget<ARMSubtarget>().hasFullFP16();
5837
5838 EVT DestVecType;
5839 if (VT == MVT::v4f32)
5840 DestVecType = MVT::v4i32;
5841 else if (VT == MVT::v4f16 && HasFullFP16)
5842 DestVecType = MVT::v4i16;
5843 else if (VT == MVT::v8f16 && HasFullFP16)
5844 DestVecType = MVT::v8i16;
5845 else
5846 return DAG.UnrollVectorOp(Op.getNode());
5847
5848 unsigned CastOpc;
5849 unsigned Opc;
5850 switch (Op.getOpcode()) {
5851 default: llvm_unreachable("Invalid opcode!");
5852 case ISD::SINT_TO_FP:
5853 CastOpc = ISD::SIGN_EXTEND;
5855 break;
5856 case ISD::UINT_TO_FP:
5857 CastOpc = ISD::ZERO_EXTEND;
5859 break;
5860 }
5861
5862 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5863 return DAG.getNode(Opc, dl, VT, Op);
5864}
5865
5866SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5867 EVT VT = Op.getValueType();
5868 if (VT.isVector())
5869 return LowerVectorINT_TO_FP(Op, DAG);
5870
5871 bool IsStrict = Op->isStrictFPOpcode();
5872 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
5873
5874 if (isUnsupportedFloatingType(VT)) {
5875 RTLIB::Libcall LC;
5876 if (Op.getOpcode() == ISD::SINT_TO_FP ||
5877 Op.getOpcode() == ISD::STRICT_SINT_TO_FP)
5878 LC = RTLIB::getSINTTOFP(SrcVal.getValueType(), Op.getValueType());
5879 else
5880 LC = RTLIB::getUINTTOFP(SrcVal.getValueType(), Op.getValueType());
5881 SDLoc Loc(Op);
5882 MakeLibCallOptions CallOptions;
5883 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
5885 std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
5886 CallOptions, Loc, Chain);
5887 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
5888 }
5889
5890 return Op;
5891}
5892
5893SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5894 // Implement fcopysign with a fabs and a conditional fneg.
5895 SDValue Tmp0 = Op.getOperand(0);
5896 SDValue Tmp1 = Op.getOperand(1);
5897 SDLoc dl(Op);
5898 EVT VT = Op.getValueType();
5899 EVT SrcVT = Tmp1.getValueType();
5900 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5901 Tmp0.getOpcode() == ARMISD::VMOVDRR;
5902 bool UseNEON = !InGPR && Subtarget->hasNEON();
5903
5904 if (UseNEON) {
5905 // Use VBSL to copy the sign bit.
5906 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5907 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5908 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5909 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5910 if (VT == MVT::f64)
5911 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5912 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5913 DAG.getConstant(32, dl, MVT::i32));
5914 else /*if (VT == MVT::f32)*/
5915 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5916 if (SrcVT == MVT::f32) {
5917 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5918 if (VT == MVT::f64)
5919 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5920 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5921 DAG.getConstant(32, dl, MVT::i32));
5922 } else if (VT == MVT::f32)
5923 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
5924 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5925 DAG.getConstant(32, dl, MVT::i32));
5926 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5927 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5928
5930 dl, MVT::i32);
5931 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5932 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5933 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5934
5935 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5936 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5937 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5938 if (VT == MVT::f32) {
5939 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5940 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5941 DAG.getConstant(0, dl, MVT::i32));
5942 } else {
5943 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5944 }
5945
5946 return Res;
5947 }
5948
5949 // Bitcast operand 1 to i32.
5950 if (SrcVT == MVT::f64)
5951 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5952 Tmp1).getValue(1);
5953 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5954
5955 // Or in the signbit with integer operations.
5956 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5957 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5958 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5959 if (VT == MVT::f32) {
5960 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5961 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5962 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5963 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5964 }
5965
5966 // f64: Or the high part with signbit and then combine two parts.
5967 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5968 Tmp0);
5969 SDValue Lo = Tmp0.getValue(0);
5970 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5971 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5972 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5973}
5974
5975SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5977 MachineFrameInfo &MFI = MF.getFrameInfo();
5978 MFI.setReturnAddressIsTaken(true);
5979
5980 EVT VT = Op.getValueType();
5981 SDLoc dl(Op);
5982 unsigned Depth = Op.getConstantOperandVal(0);
5983 if (Depth) {
5984 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5985 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5986 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5987 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5988 MachinePointerInfo());
5989 }
5990
5991 // Return LR, which contains the return address. Mark it an implicit live-in.
5992 Register Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5993 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5994}
5995
5996SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5997 const ARMBaseRegisterInfo &ARI =
5998 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
6000 MachineFrameInfo &MFI = MF.getFrameInfo();
6001 MFI.setFrameAddressIsTaken(true);
6002
6003 EVT VT = Op.getValueType();
6004 SDLoc dl(Op); // FIXME probably not meaningful
6005 unsigned Depth = Op.getConstantOperandVal(0);
6006 Register FrameReg = ARI.getFrameRegister(MF);
6007 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6008 while (Depth--)
6009 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
6010 MachinePointerInfo());
6011 return FrameAddr;
6012}
6013
6014// FIXME? Maybe this could be a TableGen attribute on some registers and
6015// this table could be generated automatically from RegInfo.
6016Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT,
6017 const MachineFunction &MF) const {
6018 return StringSwitch<Register>(RegName)
6019 .Case("sp", ARM::SP)
6020 .Default(Register());
6021}
6022
6023// Result is 64 bit value so split into two 32 bit values and return as a
6024// pair of values.
6026 SelectionDAG &DAG) {
6027 SDLoc DL(N);
6028
6029 // This function is only supposed to be called for i64 type destination.
6030 assert(N->getValueType(0) == MVT::i64
6031 && "ExpandREAD_REGISTER called for non-i64 type result.");
6032
6034 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
6035 N->getOperand(0),
6036 N->getOperand(1));
6037
6038 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
6039 Read.getValue(1)));
6040 Results.push_back(Read.getValue(2)); // Chain
6041}
6042
6043/// \p BC is a bitcast that is about to be turned into a VMOVDRR.
6044/// When \p DstVT, the destination type of \p BC, is on the vector
6045/// register bank and the source of bitcast, \p Op, operates on the same bank,
6046/// it might be possible to combine them, such that everything stays on the
6047/// vector register bank.
6048/// \p return The node that would replace \p BT, if the combine
6049/// is possible.
6051 SelectionDAG &DAG) {
6052 SDValue Op = BC->getOperand(0);
6053 EVT DstVT = BC->getValueType(0);
6054
6055 // The only vector instruction that can produce a scalar (remember,
6056 // since the bitcast was about to be turned into VMOVDRR, the source
6057 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
6058 // Moreover, we can do this combine only if there is one use.
6059 // Finally, if the destination type is not a vector, there is not
6060 // much point on forcing everything on the vector bank.
6061 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6062 !Op.hasOneUse())
6063 return SDValue();
6064
6065 // If the index is not constant, we will introduce an additional
6066 // multiply that will stick.
6067 // Give up in that case.
6068 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6069 if (!Index)
6070 return SDValue();
6071 unsigned DstNumElt = DstVT.getVectorNumElements();
6072
6073 // Compute the new index.
6074 const APInt &APIntIndex = Index->getAPIntValue();
6075 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
6076 NewIndex *= APIntIndex;
6077 // Check if the new constant index fits into i32.
6078 if (NewIndex.getBitWidth() > 32)
6079 return SDValue();
6080
6081 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
6082 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
6083 SDLoc dl(Op);
6084 SDValue ExtractSrc = Op.getOperand(0);
6085 EVT VecVT = EVT::getVectorVT(
6086 *DAG.getContext(), DstVT.getScalarType(),
6087 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
6088 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
6089 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
6090 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
6091}
6092
6093/// ExpandBITCAST - If the target supports VFP, this function is called to
6094/// expand a bit convert where either the source or destination type is i64 to
6095/// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
6096/// operand type is illegal (e.g., v2f32 for a target that doesn't support
6097/// vectors), since the legalizer won't know what to do with that.
6098SDValue ARMTargetLowering::ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
6099 const ARMSubtarget *Subtarget) const {
6100 SDLoc dl(N);
6101 SDValue Op = N->getOperand(0);
6102
6103 // This function is only supposed to be called for i16 and i64 types, either
6104 // as the source or destination of the bit convert.
6105 EVT SrcVT = Op.getValueType();
6106 EVT DstVT = N->getValueType(0);
6107
6108 if ((SrcVT == MVT::i16 || SrcVT == MVT::i32) &&
6109 (DstVT == MVT::f16 || DstVT == MVT::bf16))
6110 return MoveToHPR(SDLoc(N), DAG, MVT::i32, DstVT.getSimpleVT(),
6111 DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), MVT::i32, Op));
6112
6113 if ((DstVT == MVT::i16 || DstVT == MVT::i32) &&
6114 (SrcVT == MVT::f16 || SrcVT == MVT::bf16)) {
6115 if (Subtarget->hasFullFP16() && !Subtarget->hasBF16())
6116 Op = DAG.getBitcast(MVT::f16, Op);
6117 return DAG.getNode(
6118 ISD::TRUNCATE, SDLoc(N), DstVT,
6119 MoveFromHPR(SDLoc(N), DAG, MVT::i32, SrcVT.getSimpleVT(), Op));
6120 }
6121
6122 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
6123 return SDValue();
6124
6125 // Turn i64->f64 into VMOVDRR.
6126 if (SrcVT == MVT::i64 && isTypeLegal(DstVT)) {
6127 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
6128 // if we can combine the bitcast with its source.
6130 return Val;
6131 SDValue Lo, Hi;
6132 std::tie(Lo, Hi) = DAG.SplitScalar(Op, dl, MVT::i32, MVT::i32);
6133 return DAG.getNode(ISD::BITCAST, dl, DstVT,
6134 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
6135 }
6136
6137 // Turn f64->i64 into VMOVRRD.
6138 if (DstVT == MVT::i64 && isTypeLegal(SrcVT)) {
6139 SDValue Cvt;
6140 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
6141 SrcVT.getVectorNumElements() > 1)
6142 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6143 DAG.getVTList(MVT::i32, MVT::i32),
6144 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
6145 else
6146 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6147 DAG.getVTList(MVT::i32, MVT::i32), Op);
6148 // Merge the pieces into a single i64 value.
6149 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
6150 }
6151
6152 return SDValue();
6153}
6154
6155/// getZeroVector - Returns a vector of specified type with all zero elements.
6156/// Zero vectors are used to represent vector negation and in those cases
6157/// will be implemented with the NEON VNEG instruction. However, VNEG does
6158/// not support i64 elements, so sometimes the zero vectors will need to be
6159/// explicitly constructed. Regardless, use a canonical VMOV to create the
6160/// zero vector.
6161static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
6162 assert(VT.isVector() && "Expected a vector type");
6163 // The canonical modified immediate encoding of a zero vector is....0!
6164 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
6165 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
6166 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
6167 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6168}
6169
6170/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6171/// i32 values and take a 2 x i32 value to shift plus a shift amount.
6172SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
6173 SelectionDAG &DAG) const {
6174 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6175 EVT VT = Op.getValueType();
6176 unsigned VTBits = VT.getSizeInBits();
6177 SDLoc dl(Op);
6178 SDValue ShOpLo = Op.getOperand(0);
6179 SDValue ShOpHi = Op.getOperand(1);
6180 SDValue ShAmt = Op.getOperand(2);
6181 SDValue ARMcc;
6182 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6183
6184 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
6185
6186 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6187 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6188 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
6189 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6190 DAG.getConstant(VTBits, dl, MVT::i32));
6191 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
6192 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6193 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
6194 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6195 ISD::SETGE, ARMcc, DAG, dl);
6196 SDValue Lo =
6197 DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, ARMcc, CmpLo);
6198
6199 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
6200 SDValue HiBigShift = Opc == ISD::SRA
6201 ? DAG.getNode(Opc, dl, VT, ShOpHi,
6202 DAG.getConstant(VTBits - 1, dl, VT))
6203 : DAG.getConstant(0, dl, VT);
6204 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6205 ISD::SETGE, ARMcc, DAG, dl);
6206 SDValue Hi =
6207 DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, ARMcc, CmpHi);
6208
6209 SDValue Ops[2] = { Lo, Hi };
6210 return DAG.getMergeValues(Ops, dl);
6211}
6212
6213/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6214/// i32 values and take a 2 x i32 value to shift plus a shift amount.
6215SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
6216 SelectionDAG &DAG) const {
6217 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6218 EVT VT = Op.getValueType();
6219 unsigned VTBits = VT.getSizeInBits();
6220 SDLoc dl(Op);
6221 SDValue ShOpLo = Op.getOperand(0);
6222 SDValue ShOpHi = Op.getOperand(1);
6223 SDValue ShAmt = Op.getOperand(2);
6224 SDValue ARMcc;
6225
6226 assert(Op.getOpcode() == ISD::SHL_PARTS);
6227 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6228 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6229 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
6230 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
6231 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6232
6233 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6234 DAG.getConstant(VTBits, dl, MVT::i32));
6235 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
6236 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6237 ISD::SETGE, ARMcc, DAG, dl);
6238 SDValue Hi =
6239 DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, ARMcc, CmpHi);
6240
6241 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6242 ISD::SETGE, ARMcc, DAG, dl);
6243 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6244 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
6245 DAG.getConstant(0, dl, VT), ARMcc, CmpLo);
6246
6247 SDValue Ops[2] = { Lo, Hi };
6248 return DAG.getMergeValues(Ops, dl);
6249}
6250
6251SDValue ARMTargetLowering::LowerGET_ROUNDING(SDValue Op,
6252 SelectionDAG &DAG) const {
6253 // The rounding mode is in bits 23:22 of the FPSCR.
6254 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
6255 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
6256 // so that the shift + and get folded into a bitfield extract.
6257 SDLoc dl(Op);
6258 SDValue Chain = Op.getOperand(0);
6259 SDValue Ops[] = {Chain,
6260 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32)};
6261
6262 SDValue FPSCR =
6263 DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, {MVT::i32, MVT::Other}, Ops);
6264 Chain = FPSCR.getValue(1);
6265 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
6266 DAG.getConstant(1U << 22, dl, MVT::i32));
6267 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
6268 DAG.getConstant(22, dl, MVT::i32));
6269 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
6270 DAG.getConstant(3, dl, MVT::i32));
6271 return DAG.getMergeValues({And, Chain}, dl);
6272}
6273
6274SDValue ARMTargetLowering::LowerSET_ROUNDING(SDValue Op,
6275 SelectionDAG &DAG) const {
6276 SDLoc DL(Op);
6277 SDValue Chain = Op->getOperand(0);
6278 SDValue RMValue = Op->getOperand(1);
6279
6280 // The rounding mode is in bits 23:22 of the FPSCR.
6281 // The llvm.set.rounding argument value to ARM rounding mode value mapping
6282 // is 0->3, 1->0, 2->1, 3->2. The formula we use to implement this is
6283 // ((arg - 1) & 3) << 22).
6284 //
6285 // It is expected that the argument of llvm.set.rounding is within the
6286 // segment [0, 3], so NearestTiesToAway (4) is not handled here. It is
6287 // responsibility of the code generated llvm.set.rounding to ensure this
6288 // condition.
6289
6290 // Calculate new value of FPSCR[23:22].
6291 RMValue = DAG.getNode(ISD::SUB, DL, MVT::i32, RMValue,
6292 DAG.getConstant(1, DL, MVT::i32));
6293 RMValue = DAG.getNode(ISD::AND, DL, MVT::i32, RMValue,
6294 DAG.getConstant(0x3, DL, MVT::i32));
6295 RMValue = DAG.getNode(ISD::SHL, DL, MVT::i32, RMValue,
6296 DAG.getConstant(ARM::RoundingBitsPos, DL, MVT::i32));
6297
6298 // Get current value of FPSCR.
6299 SDValue Ops[] = {Chain,
6300 DAG.getConstant(Intrinsic::arm_get_fpscr, DL, MVT::i32)};
6301 SDValue FPSCR =
6302 DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i32, MVT::Other}, Ops);
6303 Chain = FPSCR.getValue(1);
6304 FPSCR = FPSCR.getValue(0);
6305
6306 // Put new rounding mode into FPSCR[23:22].
6307 const unsigned RMMask = ~(ARM::Rounding::rmMask << ARM::RoundingBitsPos);
6308 FPSCR = DAG.getNode(ISD::AND, DL, MVT::i32, FPSCR,
6309 DAG.getConstant(RMMask, DL, MVT::i32));
6310 FPSCR = DAG.getNode(ISD::OR, DL, MVT::i32, FPSCR, RMValue);
6311 SDValue Ops2[] = {
6312 Chain, DAG.getConstant(Intrinsic::arm_set_fpscr, DL, MVT::i32), FPSCR};
6313 return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
6314}
6315
6316SDValue ARMTargetLowering::LowerSET_FPMODE(SDValue Op,
6317 SelectionDAG &DAG) const {
6318 SDLoc DL(Op);
6319 SDValue Chain = Op->getOperand(0);
6320 SDValue Mode = Op->getOperand(1);
6321
6322 // Generate nodes to build:
6323 // FPSCR = (FPSCR & FPStatusBits) | (Mode & ~FPStatusBits)
6324 SDValue Ops[] = {Chain,
6325 DAG.getConstant(Intrinsic::arm_get_fpscr, DL, MVT::i32)};
6326 SDValue FPSCR =
6327 DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i32, MVT::Other}, Ops);
6328 Chain = FPSCR.getValue(1);
6329 FPSCR = FPSCR.getValue(0);
6330
6331 SDValue FPSCRMasked =
6332 DAG.getNode(ISD::AND, DL, MVT::i32, FPSCR,
6333 DAG.getConstant(ARM::FPStatusBits, DL, MVT::i32));
6334 SDValue InputMasked =
6335 DAG.getNode(ISD::AND, DL, MVT::i32, Mode,
6336 DAG.getConstant(~ARM::FPStatusBits, DL, MVT::i32));
6337 FPSCR = DAG.getNode(ISD::OR, DL, MVT::i32, FPSCRMasked, InputMasked);
6338
6339 SDValue Ops2[] = {
6340 Chain, DAG.getConstant(Intrinsic::arm_set_fpscr, DL, MVT::i32), FPSCR};
6341 return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
6342}
6343
6344SDValue ARMTargetLowering::LowerRESET_FPMODE(SDValue Op,
6345 SelectionDAG &DAG) const {
6346 SDLoc DL(Op);
6347 SDValue Chain = Op->getOperand(0);
6348
6349 // To get the default FP mode all control bits are cleared:
6350 // FPSCR = FPSCR & (FPStatusBits | FPReservedBits)
6351 SDValue Ops[] = {Chain,
6352 DAG.getConstant(Intrinsic::arm_get_fpscr, DL, MVT::i32)};
6353 SDValue FPSCR =
6354 DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i32, MVT::Other}, Ops);
6355 Chain = FPSCR.getValue(1);
6356 FPSCR = FPSCR.getValue(0);
6357
6358 SDValue FPSCRMasked = DAG.getNode(
6359 ISD::AND, DL, MVT::i32, FPSCR,
6361 SDValue Ops2[] = {Chain,
6362 DAG.getConstant(Intrinsic::arm_set_fpscr, DL, MVT::i32),
6363 FPSCRMasked};
6364 return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
6365}
6366
6368 const ARMSubtarget *ST) {
6369 SDLoc dl(N);
6370 EVT VT = N->getValueType(0);
6371 if (VT.isVector() && ST->hasNEON()) {
6372
6373 // Compute the least significant set bit: LSB = X & -X
6374 SDValue X = N->getOperand(0);
6375 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
6376 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
6377
6378 EVT ElemTy = VT.getVectorElementType();
6379
6380 if (ElemTy == MVT::i8) {
6381 // Compute with: cttz(x) = ctpop(lsb - 1)
6382 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6383 DAG.getTargetConstant(1, dl, ElemTy));
6384 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6385 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6386 }
6387
6388 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
6389 (N->getOpcode() == ISD::CTTZ_ZERO_POISON)) {
6390 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
6391 unsigned NumBits = ElemTy.getSizeInBits();
6392 SDValue WidthMinus1 =
6393 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6394 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
6395 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
6396 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
6397 }
6398
6399 // Compute with: cttz(x) = ctpop(lsb - 1)
6400
6401 // Compute LSB - 1.
6402 SDValue Bits;
6403 if (ElemTy == MVT::i64) {
6404 // Load constant 0xffff'ffff'ffff'ffff to register.
6405 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6406 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
6407 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
6408 } else {
6409 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6410 DAG.getTargetConstant(1, dl, ElemTy));
6411 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6412 }
6413 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6414 }
6415
6416 if (!ST->hasV6T2Ops())
6417 return SDValue();
6418
6419 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
6420 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
6421}
6422
6424 const ARMSubtarget *ST) {
6425 EVT VT = N->getValueType(0);
6426 SDLoc DL(N);
6427
6428 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
6429 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
6430 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
6431 "Unexpected type for custom ctpop lowering");
6432
6433 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6434 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
6435 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
6436 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
6437
6438 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
6439 unsigned EltSize = 8;
6440 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
6441 while (EltSize != VT.getScalarSizeInBits()) {
6443 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
6444 TLI.getPointerTy(DAG.getDataLayout())));
6445 Ops.push_back(Res);
6446
6447 EltSize *= 2;
6448 NumElts /= 2;
6449 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
6450 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
6451 }
6452
6453 return Res;
6454}
6455
6456/// Getvshiftimm - Check if this is a valid build_vector for the immediate
6457/// operand of a vector shift operation, where all the elements of the
6458/// build_vector must have the same constant integer value.
6459static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6460 // Ignore bit_converts.
6461 while (Op.getOpcode() == ISD::BITCAST)
6462 Op = Op.getOperand(0);
6464 APInt SplatBits, SplatUndef;
6465 unsigned SplatBitSize;
6466 bool HasAnyUndefs;
6467 if (!BVN ||
6468 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
6469 ElementBits) ||
6470 SplatBitSize > ElementBits)
6471 return false;
6472 Cnt = SplatBits.getSExtValue();
6473 return true;
6474}
6475
6476/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6477/// operand of a vector shift left operation. That value must be in the range:
6478/// 0 <= Value < ElementBits for a left shift; or
6479/// 0 <= Value <= ElementBits for a long left shift.
6480static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6481 assert(VT.isVector() && "vector shift count is not a vector type");
6482 int64_t ElementBits = VT.getScalarSizeInBits();
6483 if (!getVShiftImm(Op, ElementBits, Cnt))
6484 return false;
6485 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6486}
6487
6488/// isVShiftRImm - Check if this is a valid build_vector for the immediate
6489/// operand of a vector shift right operation. For a shift opcode, the value
6490/// is positive, but for an intrinsic the value count must be negative. The
6491/// absolute value must be in the range:
6492/// 1 <= |Value| <= ElementBits for a right shift; or
6493/// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
6494static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6495 int64_t &Cnt) {
6496 assert(VT.isVector() && "vector shift count is not a vector type");
6497 int64_t ElementBits = VT.getScalarSizeInBits();
6498 if (!getVShiftImm(Op, ElementBits, Cnt))
6499 return false;
6500 if (!isIntrinsic)
6501 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6502 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
6503 Cnt = -Cnt;
6504 return true;
6505 }
6506 return false;
6507}
6508
6510 const ARMSubtarget *ST) {
6511 EVT VT = N->getValueType(0);
6512 SDLoc dl(N);
6513 int64_t Cnt;
6514
6515 if (!VT.isVector())
6516 return SDValue();
6517
6518 // We essentially have two forms here. Shift by an immediate and shift by a
6519 // vector register (there are also shift by a gpr, but that is just handled
6520 // with a tablegen pattern). We cannot easily match shift by an immediate in
6521 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
6522 // For shifting by a vector, we don't have VSHR, only VSHL (which can be
6523 // signed or unsigned, and a negative shift indicates a shift right).
6524 if (N->getOpcode() == ISD::SHL) {
6525 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
6526 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
6527 DAG.getConstant(Cnt, dl, MVT::i32));
6528 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
6529 N->getOperand(1));
6530 }
6531
6532 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
6533 "unexpected vector shift opcode");
6534
6535 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
6536 unsigned VShiftOpc =
6537 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
6538 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
6539 DAG.getConstant(Cnt, dl, MVT::i32));
6540 }
6541
6542 // Other right shifts we don't have operations for (we use a shift left by a
6543 // negative number).
6544 EVT ShiftVT = N->getOperand(1).getValueType();
6545 SDValue NegatedCount = DAG.getNode(
6546 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
6547 unsigned VShiftOpc =
6548 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
6549 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
6550}
6551
6553 const ARMSubtarget *ST) {
6554 EVT VT = N->getValueType(0);
6555 SDLoc dl(N);
6556
6557 // We can get here for a node like i32 = ISD::SHL i32, i64
6558 if (VT != MVT::i64)
6559 return SDValue();
6560
6561 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
6562 N->getOpcode() == ISD::SHL) &&
6563 "Unknown shift to lower!");
6564
6565 unsigned ShOpc = N->getOpcode();
6566 if (ST->hasMVEIntegerOps()) {
6567 SDValue ShAmt = N->getOperand(1);
6568 unsigned ShPartsOpc = ARMISD::LSLL;
6570
6571 // If the shift amount is greater than 32 or has a greater bitwidth than 64
6572 // then do the default optimisation
6573 if ((!Con && ShAmt->getValueType(0).getSizeInBits() > 64) ||
6574 (Con && (Con->getAPIntValue() == 0 || Con->getAPIntValue().uge(32))))
6575 return SDValue();
6576
6577 // Extract the lower 32 bits of the shift amount if it's not an i32
6578 if (ShAmt->getValueType(0) != MVT::i32)
6579 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6580
6581 if (ShOpc == ISD::SRL) {
6582 if (!Con)
6583 // There is no t2LSRLr instruction so negate and perform an lsll if the
6584 // shift amount is in a register, emulating a right shift.
6585 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6586 DAG.getConstant(0, dl, MVT::i32), ShAmt);
6587 else
6588 // Else generate an lsrl on the immediate shift amount
6589 ShPartsOpc = ARMISD::LSRL;
6590 } else if (ShOpc == ISD::SRA)
6591 ShPartsOpc = ARMISD::ASRL;
6592
6593 // Split Lower/Upper 32 bits of the destination/source
6594 SDValue Lo, Hi;
6595 std::tie(Lo, Hi) =
6596 DAG.SplitScalar(N->getOperand(0), dl, MVT::i32, MVT::i32);
6597 // Generate the shift operation as computed above
6598 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6599 ShAmt);
6600 // The upper 32 bits come from the second return value of lsll
6601 Hi = SDValue(Lo.getNode(), 1);
6602 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6603 }
6604
6605 // We only lower SRA, SRL of 1 here, all others use generic lowering.
6606 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6607 return SDValue();
6608
6609 // If we are in thumb mode, we don't have RRX.
6610 if (ST->isThumb1Only())
6611 return SDValue();
6612
6613 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
6614 SDValue Lo, Hi;
6615 std::tie(Lo, Hi) = DAG.SplitScalar(N->getOperand(0), dl, MVT::i32, MVT::i32);
6616
6617 // First, build a LSRS1/ASRS1 op, which shifts the top part by one and
6618 // captures the shifted out bit into a carry flag.
6619 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::LSRS1 : ARMISD::ASRS1;
6620 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, FlagsVT), Hi);
6621
6622 // The low part is an ARMISD::RRX operand, which shifts the carry in.
6623 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6624
6625 // Merge the pieces into a single i64 value.
6626 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6627}
6628
6630 const ARMSubtarget *ST) {
6631 bool Invert = false;
6632 bool Swap = false;
6633 unsigned Opc = ARMCC::AL;
6634
6635 SDValue Op0 = Op.getOperand(0);
6636 SDValue Op1 = Op.getOperand(1);
6637 SDValue CC = Op.getOperand(2);
6638 EVT VT = Op.getValueType();
6639 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6640 SDLoc dl(Op);
6641
6642 EVT CmpVT;
6643 if (ST->hasNEON())
6645 else {
6646 assert(ST->hasMVEIntegerOps() &&
6647 "No hardware support for integer vector comparison!");
6648
6649 if (Op.getValueType().getVectorElementType() != MVT::i1)
6650 return SDValue();
6651
6652 // Make sure we expand floating point setcc to scalar if we do not have
6653 // mve.fp, so that we can handle them from there.
6654 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6655 return SDValue();
6656
6657 CmpVT = VT;
6658 }
6659
6660 if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6661 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6662 // Special-case integer 64-bit equality comparisons. They aren't legal,
6663 // but they can be lowered with a few vector instructions.
6664 unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6665 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6666 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6667 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6668 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6669 DAG.getCondCode(ISD::SETEQ));
6670 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6671 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6672 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6673 if (SetCCOpcode == ISD::SETNE)
6674 Merged = DAG.getNOT(dl, Merged, CmpVT);
6675 Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6676 return Merged;
6677 }
6678
6679 if (CmpVT.getVectorElementType() == MVT::i64)
6680 // 64-bit comparisons are not legal in general.
6681 return SDValue();
6682
6683 if (Op1.getValueType().isFloatingPoint()) {
6684 switch (SetCCOpcode) {
6685 default: llvm_unreachable("Illegal FP comparison");
6686 case ISD::SETUNE:
6687 case ISD::SETNE:
6688 if (ST->hasMVEFloatOps()) {
6689 Opc = ARMCC::NE; break;
6690 } else {
6691 Invert = true; [[fallthrough]];
6692 }
6693 case ISD::SETOEQ:
6694 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6695 case ISD::SETOLT:
6696 case ISD::SETLT: Swap = true; [[fallthrough]];
6697 case ISD::SETOGT:
6698 case ISD::SETGT: Opc = ARMCC::GT; break;
6699 case ISD::SETOLE:
6700 case ISD::SETLE: Swap = true; [[fallthrough]];
6701 case ISD::SETOGE:
6702 case ISD::SETGE: Opc = ARMCC::GE; break;
6703 case ISD::SETUGE: Swap = true; [[fallthrough]];
6704 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6705 case ISD::SETUGT: Swap = true; [[fallthrough]];
6706 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6707 case ISD::SETUEQ: Invert = true; [[fallthrough]];
6708 case ISD::SETONE: {
6709 // Expand this to (OLT | OGT).
6710 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6711 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6712 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6713 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6714 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6715 if (Invert)
6716 Result = DAG.getNOT(dl, Result, VT);
6717 return Result;
6718 }
6719 case ISD::SETUO: Invert = true; [[fallthrough]];
6720 case ISD::SETO: {
6721 // Expand this to (OLT | OGE).
6722 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6723 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6724 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6725 DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6726 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6727 if (Invert)
6728 Result = DAG.getNOT(dl, Result, VT);
6729 return Result;
6730 }
6731 }
6732 } else {
6733 // Integer comparisons.
6734 switch (SetCCOpcode) {
6735 default: llvm_unreachable("Illegal integer comparison");
6736 case ISD::SETNE:
6737 if (ST->hasMVEIntegerOps()) {
6738 Opc = ARMCC::NE; break;
6739 } else {
6740 Invert = true; [[fallthrough]];
6741 }
6742 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6743 case ISD::SETLT: Swap = true; [[fallthrough]];
6744 case ISD::SETGT: Opc = ARMCC::GT; break;
6745 case ISD::SETLE: Swap = true; [[fallthrough]];
6746 case ISD::SETGE: Opc = ARMCC::GE; break;
6747 case ISD::SETULT: Swap = true; [[fallthrough]];
6748 case ISD::SETUGT: Opc = ARMCC::HI; break;
6749 case ISD::SETULE: Swap = true; [[fallthrough]];
6750 case ISD::SETUGE: Opc = ARMCC::HS; break;
6751 }
6752
6753 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6754 if (ST->hasNEON() && Opc == ARMCC::EQ) {
6755 SDValue AndOp;
6757 AndOp = Op0;
6758 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6759 AndOp = Op1;
6760
6761 // Ignore bitconvert.
6762 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6763 AndOp = AndOp.getOperand(0);
6764
6765 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6766 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6767 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6768 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6769 if (!Invert)
6770 Result = DAG.getNOT(dl, Result, VT);
6771 return Result;
6772 }
6773 }
6774 }
6775
6776 if (Swap)
6777 std::swap(Op0, Op1);
6778
6779 // If one of the operands is a constant vector zero, attempt to fold the
6780 // comparison to a specialized compare-against-zero form.
6782 (Opc == ARMCC::GE || Opc == ARMCC::GT || Opc == ARMCC::EQ ||
6783 Opc == ARMCC::NE)) {
6784 if (Opc == ARMCC::GE)
6785 Opc = ARMCC::LE;
6786 else if (Opc == ARMCC::GT)
6787 Opc = ARMCC::LT;
6788 std::swap(Op0, Op1);
6789 }
6790
6791 SDValue Result;
6793 (Opc == ARMCC::GE || Opc == ARMCC::GT || Opc == ARMCC::LE ||
6794 Opc == ARMCC::LT || Opc == ARMCC::NE || Opc == ARMCC::EQ))
6795 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, Op0,
6796 DAG.getConstant(Opc, dl, MVT::i32));
6797 else
6798 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6799 DAG.getConstant(Opc, dl, MVT::i32));
6800
6801 Result = DAG.getSExtOrTrunc(Result, dl, VT);
6802
6803 if (Invert)
6804 Result = DAG.getNOT(dl, Result, VT);
6805
6806 return Result;
6807}
6808
6810 SDValue LHS = Op.getOperand(0);
6811 SDValue RHS = Op.getOperand(1);
6812
6813 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6814
6815 SDValue Carry = Op.getOperand(2);
6816 SDValue Cond = Op.getOperand(3);
6817 SDLoc DL(Op);
6818
6819 // ARMISD::SUBE expects a carry not a borrow like ISD::USUBO_CARRY so we
6820 // have to invert the carry first.
6821 SDValue InvCarry = valueToCarryFlag(Carry, DAG, true);
6822
6823 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6824 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, InvCarry);
6825
6826 SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6827 SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6828 SDValue ARMcc = DAG.getConstant(
6829 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6830 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6831 Cmp.getValue(1));
6832}
6833
6834/// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6835/// valid vector constant for a NEON or MVE instruction with a "modified
6836/// immediate" operand (e.g., VMOV). If so, return the encoded value.
6837static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6838 unsigned SplatBitSize, SelectionDAG &DAG,
6839 const SDLoc &dl, EVT &VT, EVT VectorVT,
6840 VMOVModImmType type) {
6841 unsigned OpCmode, Imm;
6842 bool is128Bits = VectorVT.is128BitVector();
6843
6844 // SplatBitSize is set to the smallest size that splats the vector, so a
6845 // zero vector will always have SplatBitSize == 8. However, NEON modified
6846 // immediate instructions others than VMOV do not support the 8-bit encoding
6847 // of a zero vector, and the default encoding of zero is supposed to be the
6848 // 32-bit version.
6849 if (SplatBits == 0)
6850 SplatBitSize = 32;
6851
6852 switch (SplatBitSize) {
6853 case 8:
6854 if (type != VMOVModImm)
6855 return SDValue();
6856 // Any 1-byte value is OK. Op=0, Cmode=1110.
6857 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6858 OpCmode = 0xe;
6859 Imm = SplatBits;
6860 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6861 break;
6862
6863 case 16:
6864 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6865 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6866 if ((SplatBits & ~0xff) == 0) {
6867 // Value = 0x00nn: Op=x, Cmode=100x.
6868 OpCmode = 0x8;
6869 Imm = SplatBits;
6870 break;
6871 }
6872 if ((SplatBits & ~0xff00) == 0) {
6873 // Value = 0xnn00: Op=x, Cmode=101x.
6874 OpCmode = 0xa;
6875 Imm = SplatBits >> 8;
6876 break;
6877 }
6878 return SDValue();
6879
6880 case 32:
6881 // NEON's 32-bit VMOV supports splat values where:
6882 // * only one byte is nonzero, or
6883 // * the least significant byte is 0xff and the second byte is nonzero, or
6884 // * the least significant 2 bytes are 0xff and the third is nonzero.
6885 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6886 if ((SplatBits & ~0xff) == 0) {
6887 // Value = 0x000000nn: Op=x, Cmode=000x.
6888 OpCmode = 0;
6889 Imm = SplatBits;
6890 break;
6891 }
6892 if ((SplatBits & ~0xff00) == 0) {
6893 // Value = 0x0000nn00: Op=x, Cmode=001x.
6894 OpCmode = 0x2;
6895 Imm = SplatBits >> 8;
6896 break;
6897 }
6898 if ((SplatBits & ~0xff0000) == 0) {
6899 // Value = 0x00nn0000: Op=x, Cmode=010x.
6900 OpCmode = 0x4;
6901 Imm = SplatBits >> 16;
6902 break;
6903 }
6904 if ((SplatBits & ~0xff000000) == 0) {
6905 // Value = 0xnn000000: Op=x, Cmode=011x.
6906 OpCmode = 0x6;
6907 Imm = SplatBits >> 24;
6908 break;
6909 }
6910
6911 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6912 if (type == OtherModImm) return SDValue();
6913
6914 if ((SplatBits & ~0xffff) == 0 &&
6915 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6916 // Value = 0x0000nnff: Op=x, Cmode=1100.
6917 OpCmode = 0xc;
6918 Imm = SplatBits >> 8;
6919 break;
6920 }
6921
6922 // cmode == 0b1101 is not supported for MVE VMVN
6923 if (type == MVEVMVNModImm)
6924 return SDValue();
6925
6926 if ((SplatBits & ~0xffffff) == 0 &&
6927 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6928 // Value = 0x00nnffff: Op=x, Cmode=1101.
6929 OpCmode = 0xd;
6930 Imm = SplatBits >> 16;
6931 break;
6932 }
6933
6934 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6935 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6936 // VMOV.I32. A (very) minor optimization would be to replicate the value
6937 // and fall through here to test for a valid 64-bit splat. But, then the
6938 // caller would also need to check and handle the change in size.
6939 return SDValue();
6940
6941 case 64: {
6942 if (type != VMOVModImm)
6943 return SDValue();
6944 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6945 uint64_t BitMask = 0xff;
6946 unsigned ImmMask = 1;
6947 Imm = 0;
6948 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6949 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6950 Imm |= ImmMask;
6951 } else if ((SplatBits & BitMask) != 0) {
6952 return SDValue();
6953 }
6954 BitMask <<= 8;
6955 ImmMask <<= 1;
6956 }
6957
6958 // Op=1, Cmode=1110.
6959 OpCmode = 0x1e;
6960 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6961 break;
6962 }
6963
6964 default:
6965 llvm_unreachable("unexpected size for isVMOVModifiedImm");
6966 }
6967
6968 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
6969 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
6970}
6971
6972SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6973 const ARMSubtarget *ST) const {
6974 EVT VT = Op.getValueType();
6975 bool IsDouble = (VT == MVT::f64);
6976 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
6977 const APFloat &FPVal = CFP->getValueAPF();
6978
6979 // Prevent floating-point constants from using literal loads
6980 // when execute-only is enabled.
6981 if (ST->genExecuteOnly()) {
6982 // We shouldn't trigger this for v6m execute-only
6983 assert((!ST->isThumb1Only() || ST->hasV8MBaselineOps()) &&
6984 "Unexpected architecture");
6985
6986 // If we can represent the constant as an immediate, don't lower it
6987 if (isFPImmLegal(FPVal, VT))
6988 return Op;
6989 // Otherwise, construct as integer, and move to float register
6990 APInt INTVal = FPVal.bitcastToAPInt();
6991 SDLoc DL(CFP);
6992 switch (VT.getSimpleVT().SimpleTy) {
6993 default:
6994 llvm_unreachable("Unknown floating point type!");
6995 break;
6996 case MVT::f64: {
6997 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
6998 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
6999 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
7000 }
7001 case MVT::f32:
7002 return DAG.getNode(ARMISD::VMOVSR, DL, VT,
7003 DAG.getConstant(INTVal, DL, MVT::i32));
7004 }
7005 }
7006
7007 if (!ST->hasVFP3Base())
7008 return SDValue();
7009
7010 // Use the default (constant pool) lowering for double constants when we have
7011 // an SP-only FPU
7012 if (IsDouble && !Subtarget->hasFP64())
7013 return SDValue();
7014
7015 // Try splatting with a VMOV.f32...
7016 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
7017
7018 if (ImmVal != -1) {
7019 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
7020 // We have code in place to select a valid ConstantFP already, no need to
7021 // do any mangling.
7022 return Op;
7023 }
7024
7025 // It's a float and we are trying to use NEON operations where
7026 // possible. Lower it to a splat followed by an extract.
7027 SDLoc DL(Op);
7028 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
7029 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
7030 NewVal);
7031 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
7032 DAG.getConstant(0, DL, MVT::i32));
7033 }
7034
7035 // The rest of our options are NEON only, make sure that's allowed before
7036 // proceeding..
7037 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
7038 return SDValue();
7039
7040 EVT VMovVT;
7041 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
7042
7043 // It wouldn't really be worth bothering for doubles except for one very
7044 // important value, which does happen to match: 0.0. So make sure we don't do
7045 // anything stupid.
7046 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
7047 return SDValue();
7048
7049 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
7050 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
7051 VMovVT, VT, VMOVModImm);
7052 if (NewVal != SDValue()) {
7053 SDLoc DL(Op);
7054 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
7055 NewVal);
7056 if (IsDouble)
7057 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
7058
7059 // It's a float: cast and extract a vector element.
7060 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
7061 VecConstant);
7062 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
7063 DAG.getConstant(0, DL, MVT::i32));
7064 }
7065
7066 // Finally, try a VMVN.i32
7067 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
7068 VT, VMVNModImm);
7069 if (NewVal != SDValue()) {
7070 SDLoc DL(Op);
7071 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
7072
7073 if (IsDouble)
7074 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
7075
7076 // It's a float: cast and extract a vector element.
7077 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
7078 VecConstant);
7079 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
7080 DAG.getConstant(0, DL, MVT::i32));
7081 }
7082
7083 return SDValue();
7084}
7085
7086// check if an VEXT instruction can handle the shuffle mask when the
7087// vector sources of the shuffle are the same.
7088static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
7089 unsigned NumElts = VT.getVectorNumElements();
7090
7091 // Assume that the first shuffle index is not UNDEF. Fail if it is.
7092 if (M[0] < 0)
7093 return false;
7094
7095 Imm = M[0];
7096
7097 // If this is a VEXT shuffle, the immediate value is the index of the first
7098 // element. The other shuffle indices must be the successive elements after
7099 // the first one.
7100 unsigned ExpectedElt = Imm;
7101 for (unsigned i = 1; i < NumElts; ++i) {
7102 // Increment the expected index. If it wraps around, just follow it
7103 // back to index zero and keep going.
7104 ++ExpectedElt;
7105 if (ExpectedElt == NumElts)
7106 ExpectedElt = 0;
7107
7108 if (M[i] < 0) continue; // ignore UNDEF indices
7109 if (ExpectedElt != static_cast<unsigned>(M[i]))
7110 return false;
7111 }
7112
7113 return true;
7114}
7115
7116static bool isVEXTMask(ArrayRef<int> M, EVT VT,
7117 bool &ReverseVEXT, unsigned &Imm) {
7118 unsigned NumElts = VT.getVectorNumElements();
7119 ReverseVEXT = false;
7120
7121 // Assume that the first shuffle index is not UNDEF. Fail if it is.
7122 if (M[0] < 0)
7123 return false;
7124
7125 Imm = M[0];
7126
7127 // If this is a VEXT shuffle, the immediate value is the index of the first
7128 // element. The other shuffle indices must be the successive elements after
7129 // the first one.
7130 unsigned ExpectedElt = Imm;
7131 for (unsigned i = 1; i < NumElts; ++i) {
7132 // Increment the expected index. If it wraps around, it may still be
7133 // a VEXT but the source vectors must be swapped.
7134 ExpectedElt += 1;
7135 if (ExpectedElt == NumElts * 2) {
7136 ExpectedElt = 0;
7137 ReverseVEXT = true;
7138 }
7139
7140 if (M[i] < 0) continue; // ignore UNDEF indices
7141 if (ExpectedElt != static_cast<unsigned>(M[i]))
7142 return false;
7143 }
7144
7145 // Adjust the index value if the source operands will be swapped.
7146 if (ReverseVEXT)
7147 Imm -= NumElts;
7148
7149 return true;
7150}
7151
7152static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
7153 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
7154 // range, then 0 is placed into the resulting vector. So pretty much any mask
7155 // of 8 elements can work here.
7156 return VT == MVT::v8i8 && M.size() == 8;
7157}
7158
7159static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
7160 unsigned Index) {
7161 if (Mask.size() == Elements * 2)
7162 return Index / Elements;
7163 return Mask[Index] == 0 ? 0 : 1;
7164}
7165
7166// Checks whether the shuffle mask represents a vector transpose (VTRN) by
7167// checking that pairs of elements in the shuffle mask represent the same index
7168// in each vector, incrementing the expected index by 2 at each step.
7169// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
7170// v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
7171// v2={e,f,g,h}
7172// WhichResult gives the offset for each element in the mask based on which
7173// of the two results it belongs to.
7174//
7175// The transpose can be represented either as:
7176// result1 = shufflevector v1, v2, result1_shuffle_mask
7177// result2 = shufflevector v1, v2, result2_shuffle_mask
7178// where v1/v2 and the shuffle masks have the same number of elements
7179// (here WhichResult (see below) indicates which result is being checked)
7180//
7181// or as:
7182// results = shufflevector v1, v2, shuffle_mask
7183// where both results are returned in one vector and the shuffle mask has twice
7184// as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
7185// want to check the low half and high half of the shuffle mask as if it were
7186// the other case
7187static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7188 unsigned EltSz = VT.getScalarSizeInBits();
7189 if (EltSz == 64)
7190 return false;
7191
7192 unsigned NumElts = VT.getVectorNumElements();
7193 if ((M.size() != NumElts && M.size() != NumElts * 2) || NumElts % 2 != 0)
7194 return false;
7195
7196 // If the mask is twice as long as the input vector then we need to check the
7197 // upper and lower parts of the mask with a matching value for WhichResult
7198 // FIXME: A mask with only even values will be rejected in case the first
7199 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
7200 // M[0] is used to determine WhichResult
7201 for (unsigned i = 0; i < M.size(); i += NumElts) {
7202 WhichResult = SelectPairHalf(NumElts, M, i);
7203 for (unsigned j = 0; j < NumElts; j += 2) {
7204 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7205 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
7206 return false;
7207 }
7208 }
7209
7210 if (M.size() == NumElts*2)
7211 WhichResult = 0;
7212
7213 return true;
7214}
7215
7216/// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
7217/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7218/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
7219static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7220 unsigned EltSz = VT.getScalarSizeInBits();
7221 if (EltSz == 64)
7222 return false;
7223
7224 unsigned NumElts = VT.getVectorNumElements();
7225 if ((M.size() != NumElts && M.size() != NumElts * 2) || NumElts % 2 != 0)
7226 return false;
7227
7228 for (unsigned i = 0; i < M.size(); i += NumElts) {
7229 WhichResult = SelectPairHalf(NumElts, M, i);
7230 for (unsigned j = 0; j < NumElts; j += 2) {
7231 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7232 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
7233 return false;
7234 }
7235 }
7236
7237 if (M.size() == NumElts*2)
7238 WhichResult = 0;
7239
7240 return true;
7241}
7242
7243// Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
7244// that the mask elements are either all even and in steps of size 2 or all odd
7245// and in steps of size 2.
7246// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
7247// v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
7248// v2={e,f,g,h}
7249// Requires similar checks to that of isVTRNMask with
7250// respect the how results are returned.
7251static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7252 unsigned EltSz = VT.getScalarSizeInBits();
7253 if (EltSz == 64)
7254 return false;
7255
7256 unsigned NumElts = VT.getVectorNumElements();
7257 if (M.size() != NumElts && M.size() != NumElts*2)
7258 return false;
7259
7260 for (unsigned i = 0; i < M.size(); i += NumElts) {
7261 WhichResult = SelectPairHalf(NumElts, M, i);
7262 for (unsigned j = 0; j < NumElts; ++j) {
7263 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
7264 return false;
7265 }
7266 }
7267
7268 if (M.size() == NumElts*2)
7269 WhichResult = 0;
7270
7271 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7272 if (VT.is64BitVector() && EltSz == 32)
7273 return false;
7274
7275 return true;
7276}
7277
7278/// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
7279/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7280/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
7281static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7282 unsigned EltSz = VT.getScalarSizeInBits();
7283 if (EltSz == 64)
7284 return false;
7285
7286 unsigned NumElts = VT.getVectorNumElements();
7287 if (M.size() != NumElts && M.size() != NumElts*2)
7288 return false;
7289
7290 unsigned Half = NumElts / 2;
7291 for (unsigned i = 0; i < M.size(); i += NumElts) {
7292 WhichResult = SelectPairHalf(NumElts, M, i);
7293 for (unsigned j = 0; j < NumElts; j += Half) {
7294 unsigned Idx = WhichResult;
7295 for (unsigned k = 0; k < Half; ++k) {
7296 int MIdx = M[i + j + k];
7297 if (MIdx >= 0 && (unsigned) MIdx != Idx)
7298 return false;
7299 Idx += 2;
7300 }
7301 }
7302 }
7303
7304 if (M.size() == NumElts*2)
7305 WhichResult = 0;
7306
7307 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7308 if (VT.is64BitVector() && EltSz == 32)
7309 return false;
7310
7311 return true;
7312}
7313
7314// Checks whether the shuffle mask represents a vector zip (VZIP) by checking
7315// that pairs of elements of the shufflemask represent the same index in each
7316// vector incrementing sequentially through the vectors.
7317// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
7318// v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
7319// v2={e,f,g,h}
7320// Requires similar checks to that of isVTRNMask with respect the how results
7321// are returned.
7322static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7323 unsigned EltSz = VT.getScalarSizeInBits();
7324 if (EltSz == 64)
7325 return false;
7326
7327 unsigned NumElts = VT.getVectorNumElements();
7328 if ((M.size() != NumElts && M.size() != NumElts * 2) || NumElts % 2 != 0)
7329 return false;
7330
7331 for (unsigned i = 0; i < M.size(); i += NumElts) {
7332 WhichResult = SelectPairHalf(NumElts, M, i);
7333 unsigned Idx = WhichResult * NumElts / 2;
7334 for (unsigned j = 0; j < NumElts; j += 2) {
7335 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7336 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
7337 return false;
7338 Idx += 1;
7339 }
7340 }
7341
7342 if (M.size() == NumElts*2)
7343 WhichResult = 0;
7344
7345 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7346 if (VT.is64BitVector() && EltSz == 32)
7347 return false;
7348
7349 return true;
7350}
7351
7352/// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
7353/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7354/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
7355static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7356 unsigned EltSz = VT.getScalarSizeInBits();
7357 if (EltSz == 64)
7358 return false;
7359
7360 unsigned NumElts = VT.getVectorNumElements();
7361 if ((M.size() != NumElts && M.size() != NumElts * 2) || NumElts % 2 != 0)
7362 return false;
7363
7364 for (unsigned i = 0; i < M.size(); i += NumElts) {
7365 WhichResult = SelectPairHalf(NumElts, M, i);
7366 unsigned Idx = WhichResult * NumElts / 2;
7367 for (unsigned j = 0; j < NumElts; j += 2) {
7368 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7369 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
7370 return false;
7371 Idx += 1;
7372 }
7373 }
7374
7375 if (M.size() == NumElts*2)
7376 WhichResult = 0;
7377
7378 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7379 if (VT.is64BitVector() && EltSz == 32)
7380 return false;
7381
7382 return true;
7383}
7384
7385/// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
7386/// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
7387static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
7388 unsigned &WhichResult,
7389 bool &isV_UNDEF) {
7390 isV_UNDEF = false;
7391 if (isVTRNMask(ShuffleMask, VT, WhichResult))
7392 return ARMISD::VTRN;
7393 if (isVUZPMask(ShuffleMask, VT, WhichResult))
7394 return ARMISD::VUZP;
7395 if (isVZIPMask(ShuffleMask, VT, WhichResult))
7396 return ARMISD::VZIP;
7397
7398 isV_UNDEF = true;
7399 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
7400 return ARMISD::VTRN;
7401 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7402 return ARMISD::VUZP;
7403 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7404 return ARMISD::VZIP;
7405
7406 return 0;
7407}
7408
7409/// \return true if this is a reverse operation on an vector.
7410static bool isReverseMask(ArrayRef<int> M, EVT VT) {
7411 unsigned NumElts = VT.getVectorNumElements();
7412 // Make sure the mask has the right size.
7413 if (NumElts != M.size())
7414 return false;
7415
7416 // Look for <15, ..., 3, -1, 1, 0>.
7417 for (unsigned i = 0; i != NumElts; ++i)
7418 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
7419 return false;
7420
7421 return true;
7422}
7423
7424static bool isTruncMask(ArrayRef<int> M, EVT VT, bool Top, bool SingleSource) {
7425 unsigned NumElts = VT.getVectorNumElements();
7426 // Make sure the mask has the right size.
7427 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7428 return false;
7429
7430 // Half-width truncation patterns (e.g. v4i32 -> v8i16):
7431 // !Top && SingleSource: <0, 2, 4, 6, 0, 2, 4, 6>
7432 // !Top && !SingleSource: <0, 2, 4, 6, 8, 10, 12, 14>
7433 // Top && SingleSource: <1, 3, 5, 7, 1, 3, 5, 7>
7434 // Top && !SingleSource: <1, 3, 5, 7, 9, 11, 13, 15>
7435 int Ofs = Top ? 1 : 0;
7436 int Upper = SingleSource ? 0 : NumElts;
7437 for (int i = 0, e = NumElts / 2; i != e; ++i) {
7438 if (M[i] >= 0 && M[i] != (i * 2) + Ofs)
7439 return false;
7440 if (M[i + e] >= 0 && M[i + e] != (i * 2) + Ofs + Upper)
7441 return false;
7442 }
7443 return true;
7444}
7445
7446static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top, bool SingleSource) {
7447 unsigned NumElts = VT.getVectorNumElements();
7448 // Make sure the mask has the right size.
7449 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7450 return false;
7451
7452 // If Top
7453 // Look for <0, N, 2, N+2, 4, N+4, ..>.
7454 // This inserts Input2 into Input1
7455 // else if not Top
7456 // Look for <0, N+1, 2, N+3, 4, N+5, ..>
7457 // This inserts Input1 into Input2
7458 unsigned Offset = Top ? 0 : 1;
7459 unsigned N = SingleSource ? 0 : NumElts;
7460 for (unsigned i = 0; i < NumElts; i += 2) {
7461 if (M[i] >= 0 && M[i] != (int)i)
7462 return false;
7463 if (M[i + 1] >= 0 && M[i + 1] != (int)(N + i + Offset))
7464 return false;
7465 }
7466
7467 return true;
7468}
7469
7470static bool isVMOVNTruncMask(ArrayRef<int> M, EVT ToVT, bool rev) {
7471 unsigned NumElts = ToVT.getVectorNumElements();
7472 if (NumElts != M.size())
7473 return false;
7474
7475 // Test if the Trunc can be convertible to a VMOVN with this shuffle. We are
7476 // looking for patterns of:
7477 // !rev: 0 N/2 1 N/2+1 2 N/2+2 ...
7478 // rev: N/2 0 N/2+1 1 N/2+2 2 ...
7479
7480 unsigned Off0 = rev ? NumElts / 2 : 0;
7481 unsigned Off1 = rev ? 0 : NumElts / 2;
7482 for (unsigned i = 0; i < NumElts; i += 2) {
7483 if (M[i] >= 0 && M[i] != (int)(Off0 + i / 2))
7484 return false;
7485 if (M[i + 1] >= 0 && M[i + 1] != (int)(Off1 + i / 2))
7486 return false;
7487 }
7488
7489 return true;
7490}
7491
7492// Reconstruct an MVE VCVT from a BuildVector of scalar fptrunc, all extracted
7493// from a pair of inputs. For example:
7494// BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7495// FP_ROUND(EXTRACT_ELT(Y, 0),
7496// FP_ROUND(EXTRACT_ELT(X, 1),
7497// FP_ROUND(EXTRACT_ELT(Y, 1), ...)
7499 const ARMSubtarget *ST) {
7500 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7501 if (!ST->hasMVEFloatOps())
7502 return SDValue();
7503
7504 SDLoc dl(BV);
7505 EVT VT = BV.getValueType();
7506 if (VT != MVT::v8f16)
7507 return SDValue();
7508
7509 // We are looking for a buildvector of fptrunc elements, where all the
7510 // elements are interleavingly extracted from two sources. Check the first two
7511 // items are valid enough and extract some info from them (they are checked
7512 // properly in the loop below).
7513 if (BV.getOperand(0).getOpcode() != ISD::FP_ROUND ||
7516 return SDValue();
7517 if (BV.getOperand(1).getOpcode() != ISD::FP_ROUND ||
7520 return SDValue();
7521 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7522 SDValue Op1 = BV.getOperand(1).getOperand(0).getOperand(0);
7523 if (Op0.getValueType() != MVT::v4f32 || Op1.getValueType() != MVT::v4f32)
7524 return SDValue();
7525
7526 // Check all the values in the BuildVector line up with our expectations.
7527 for (unsigned i = 1; i < 4; i++) {
7528 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7529 return Trunc.getOpcode() == ISD::FP_ROUND &&
7531 Trunc.getOperand(0).getOperand(0) == Op &&
7532 Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7533 };
7534 if (!Check(BV.getOperand(i * 2 + 0), Op0, i))
7535 return SDValue();
7536 if (!Check(BV.getOperand(i * 2 + 1), Op1, i))
7537 return SDValue();
7538 }
7539
7540 SDValue N1 = DAG.getNode(ARMISD::VCVTN, dl, VT, DAG.getUNDEF(VT), Op0,
7541 DAG.getConstant(0, dl, MVT::i32));
7542 return DAG.getNode(ARMISD::VCVTN, dl, VT, N1, Op1,
7543 DAG.getConstant(1, dl, MVT::i32));
7544}
7545
7546// Reconstruct an MVE VCVT from a BuildVector of scalar fpext, all extracted
7547// from a single input on alternating lanes. For example:
7548// BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7549// FP_ROUND(EXTRACT_ELT(X, 2),
7550// FP_ROUND(EXTRACT_ELT(X, 4), ...)
7552 const ARMSubtarget *ST) {
7553 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7554 if (!ST->hasMVEFloatOps())
7555 return SDValue();
7556
7557 SDLoc dl(BV);
7558 EVT VT = BV.getValueType();
7559 if (VT != MVT::v4f32)
7560 return SDValue();
7561
7562 // We are looking for a buildvector of fptext elements, where all the
7563 // elements are alternating lanes from a single source. For example <0,2,4,6>
7564 // or <1,3,5,7>. Check the first two items are valid enough and extract some
7565 // info from them (they are checked properly in the loop below).
7566 if (BV.getOperand(0).getOpcode() != ISD::FP_EXTEND ||
7568 return SDValue();
7569 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7571 if (Op0.getValueType() != MVT::v8f16 || (Offset != 0 && Offset != 1))
7572 return SDValue();
7573
7574 // Check all the values in the BuildVector line up with our expectations.
7575 for (unsigned i = 1; i < 4; i++) {
7576 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7577 return Trunc.getOpcode() == ISD::FP_EXTEND &&
7579 Trunc.getOperand(0).getOperand(0) == Op &&
7580 Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7581 };
7582 if (!Check(BV.getOperand(i), Op0, 2 * i + Offset))
7583 return SDValue();
7584 }
7585
7586 return DAG.getNode(ARMISD::VCVTL, dl, VT, Op0,
7587 DAG.getConstant(Offset, dl, MVT::i32));
7588}
7589
7590// If N is an integer constant that can be moved into a register in one
7591// instruction, return an SDValue of such a constant (will become a MOV
7592// instruction). Otherwise return null.
7594 const ARMSubtarget *ST, const SDLoc &dl) {
7595 uint64_t Val;
7596 if (!isa<ConstantSDNode>(N))
7597 return SDValue();
7598 Val = N->getAsZExtVal();
7599
7600 if (ST->isThumb1Only()) {
7601 if (Val <= 255 || ~Val <= 255)
7602 return DAG.getConstant(Val, dl, MVT::i32);
7603 } else {
7604 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
7605 return DAG.getConstant(Val, dl, MVT::i32);
7606 }
7607 return SDValue();
7608}
7609
7611 const ARMSubtarget *ST) {
7612 SDLoc dl(Op);
7613 EVT VT = Op.getValueType();
7614
7615 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
7616
7617 unsigned NumElts = VT.getVectorNumElements();
7618 unsigned BoolMask;
7619 unsigned BitsPerBool;
7620 if (NumElts == 2) {
7621 BitsPerBool = 8;
7622 BoolMask = 0xff;
7623 } else if (NumElts == 4) {
7624 BitsPerBool = 4;
7625 BoolMask = 0xf;
7626 } else if (NumElts == 8) {
7627 BitsPerBool = 2;
7628 BoolMask = 0x3;
7629 } else if (NumElts == 16) {
7630 BitsPerBool = 1;
7631 BoolMask = 0x1;
7632 } else
7633 return SDValue();
7634
7635 // If this is a single value copied into all lanes (a splat), we can just sign
7636 // extend that single value
7637 SDValue FirstOp = Op.getOperand(0);
7638 if (!isa<ConstantSDNode>(FirstOp) &&
7639 llvm::all_of(llvm::drop_begin(Op->ops()), [&FirstOp](const SDUse &U) {
7640 return U.get().isUndef() || U.get() == FirstOp;
7641 })) {
7642 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp,
7643 DAG.getValueType(MVT::i1));
7644 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext);
7645 }
7646
7647 // First create base with bits set where known
7648 unsigned Bits32 = 0;
7649 for (unsigned i = 0; i < NumElts; ++i) {
7650 SDValue V = Op.getOperand(i);
7651 if (!isa<ConstantSDNode>(V) && !V.isUndef())
7652 continue;
7653 bool BitSet = V.isUndef() ? false : V->getAsZExtVal();
7654 if (BitSet)
7655 Bits32 |= BoolMask << (i * BitsPerBool);
7656 }
7657
7658 // Add in unknown nodes
7659 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
7660 DAG.getConstant(Bits32, dl, MVT::i32));
7661 for (unsigned i = 0; i < NumElts; ++i) {
7662 SDValue V = Op.getOperand(i);
7663 if (isa<ConstantSDNode>(V) || V.isUndef())
7664 continue;
7665 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
7666 DAG.getConstant(i, dl, MVT::i32));
7667 }
7668
7669 return Base;
7670}
7671
7673 const ARMSubtarget *ST) {
7674 if (!ST->hasMVEIntegerOps())
7675 return SDValue();
7676
7677 // We are looking for a buildvector where each element is Op[0] + i*N
7678 EVT VT = Op.getValueType();
7679 SDValue Op0 = Op.getOperand(0);
7680 unsigned NumElts = VT.getVectorNumElements();
7681
7682 // Get the increment value from operand 1
7683 SDValue Op1 = Op.getOperand(1);
7684 if (Op1.getOpcode() != ISD::ADD || Op1.getOperand(0) != Op0 ||
7686 return SDValue();
7687 unsigned N = Op1.getConstantOperandVal(1);
7688 if (N != 1 && N != 2 && N != 4 && N != 8)
7689 return SDValue();
7690
7691 // Check that each other operand matches
7692 for (unsigned I = 2; I < NumElts; I++) {
7693 SDValue OpI = Op.getOperand(I);
7694 if (OpI.getOpcode() != ISD::ADD || OpI.getOperand(0) != Op0 ||
7696 OpI.getConstantOperandVal(1) != I * N)
7697 return SDValue();
7698 }
7699
7700 SDLoc DL(Op);
7701 return DAG.getNode(ARMISD::VIDUP, DL, DAG.getVTList(VT, MVT::i32), Op0,
7702 DAG.getConstant(N, DL, MVT::i32));
7703}
7704
7705// Returns true if the operation N can be treated as qr instruction variant at
7706// operand Op.
7707static bool IsQRMVEInstruction(const SDNode *N, const SDNode *Op) {
7708 switch (N->getOpcode()) {
7709 case ISD::ADD:
7710 case ISD::MUL:
7711 case ISD::SADDSAT:
7712 case ISD::UADDSAT:
7713 case ISD::AVGFLOORS:
7714 case ISD::AVGFLOORU:
7715 return true;
7716 case ISD::SUB:
7717 case ISD::SSUBSAT:
7718 case ISD::USUBSAT:
7719 return N->getOperand(1).getNode() == Op;
7721 switch (N->getConstantOperandVal(0)) {
7722 case Intrinsic::arm_mve_add_predicated:
7723 case Intrinsic::arm_mve_mul_predicated:
7724 case Intrinsic::arm_mve_qadd_predicated:
7725 case Intrinsic::arm_mve_vhadd:
7726 case Intrinsic::arm_mve_hadd_predicated:
7727 case Intrinsic::arm_mve_vqdmulh:
7728 case Intrinsic::arm_mve_qdmulh_predicated:
7729 case Intrinsic::arm_mve_vqrdmulh:
7730 case Intrinsic::arm_mve_qrdmulh_predicated:
7731 case Intrinsic::arm_mve_vqdmull:
7732 case Intrinsic::arm_mve_vqdmull_predicated:
7733 return true;
7734 case Intrinsic::arm_mve_sub_predicated:
7735 case Intrinsic::arm_mve_qsub_predicated:
7736 case Intrinsic::arm_mve_vhsub:
7737 case Intrinsic::arm_mve_hsub_predicated:
7738 return N->getOperand(2).getNode() == Op;
7739 default:
7740 return false;
7741 }
7742 default:
7743 return false;
7744 }
7745}
7746
7747// If this is a case we can't handle, return null and let the default
7748// expansion code take care of it.
7749SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
7750 const ARMSubtarget *ST) const {
7751 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7752 SDLoc dl(Op);
7753 EVT VT = Op.getValueType();
7754
7755 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7756 return LowerBUILD_VECTOR_i1(Op, DAG, ST);
7757
7758 if (SDValue R = LowerBUILD_VECTORToVIDUP(Op, DAG, ST))
7759 return R;
7760
7761 APInt SplatBits, SplatUndef;
7762 unsigned SplatBitSize;
7763 bool HasAnyUndefs;
7764 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7765 if (SplatUndef.isAllOnes())
7766 return DAG.getUNDEF(VT);
7767
7768 // If all the users of this constant splat are qr instruction variants,
7769 // generate a vdup of the constant.
7770 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == SplatBitSize &&
7771 (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32) &&
7772 all_of(BVN->users(),
7773 [BVN](const SDNode *U) { return IsQRMVEInstruction(U, BVN); })) {
7774 EVT DupVT = SplatBitSize == 32 ? MVT::v4i32
7775 : SplatBitSize == 16 ? MVT::v8i16
7776 : MVT::v16i8;
7777 SDValue Const = DAG.getConstant(SplatBits.getZExtValue(), dl, MVT::i32);
7778 SDValue VDup = DAG.getNode(ARMISD::VDUP, dl, DupVT, Const);
7779 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, VDup);
7780 }
7781
7782 if ((ST->hasNEON() && SplatBitSize <= 64) ||
7783 (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) {
7784 // Check if an immediate VMOV works.
7785 EVT VmovVT;
7786 SDValue Val =
7787 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
7788 SplatBitSize, DAG, dl, VmovVT, VT, VMOVModImm);
7789
7790 if (Val.getNode()) {
7791 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
7792 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Vmov);
7793 }
7794
7795 // Try an immediate VMVN.
7796 uint64_t NegatedImm = (~SplatBits).getZExtValue();
7797 Val = isVMOVModifiedImm(
7798 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VmovVT,
7799 VT, ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
7800 if (Val.getNode()) {
7801 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
7802 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Vmov);
7803 }
7804
7805 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7806 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7807 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
7808 if (ImmVal != -1) {
7809 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
7810 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
7811 }
7812 }
7813
7814 // If we are under MVE, generate a VDUP(constant), bitcast to the original
7815 // type.
7816 if (ST->hasMVEIntegerOps() &&
7817 (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32)) {
7818 EVT DupVT = SplatBitSize == 32 ? MVT::v4i32
7819 : SplatBitSize == 16 ? MVT::v8i16
7820 : MVT::v16i8;
7821 SDValue Const = DAG.getConstant(SplatBits.getZExtValue(), dl, MVT::i32);
7822 SDValue VDup = DAG.getNode(ARMISD::VDUP, dl, DupVT, Const);
7823 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, VDup);
7824 }
7825 }
7826 }
7827
7828 // Scan through the operands to see if only one value is used.
7829 //
7830 // As an optimisation, even if more than one value is used it may be more
7831 // profitable to splat with one value then change some lanes.
7832 //
7833 // Heuristically we decide to do this if the vector has a "dominant" value,
7834 // defined as splatted to more than half of the lanes.
7835 unsigned NumElts = VT.getVectorNumElements();
7836 bool isOnlyLowElement = true;
7837 bool usesOnlyOneValue = true;
7838 bool hasDominantValue = false;
7839 bool isConstant = true;
7840
7841 // Map of the number of times a particular SDValue appears in the
7842 // element list.
7843 DenseMap<SDValue, unsigned> ValueCounts;
7844 SDValue Value;
7845 for (unsigned i = 0; i < NumElts; ++i) {
7846 SDValue V = Op.getOperand(i);
7847 if (V.isUndef())
7848 continue;
7849 if (i > 0)
7850 isOnlyLowElement = false;
7852 isConstant = false;
7853
7854 unsigned &Count = ValueCounts[V];
7855
7856 // Is this value dominant? (takes up more than half of the lanes)
7857 if (++Count > (NumElts / 2)) {
7858 hasDominantValue = true;
7859 Value = V;
7860 }
7861 }
7862 if (ValueCounts.size() != 1)
7863 usesOnlyOneValue = false;
7864 if (!Value.getNode() && !ValueCounts.empty())
7865 Value = ValueCounts.begin()->first;
7866
7867 if (ValueCounts.empty())
7868 return DAG.getUNDEF(VT);
7869
7870 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7871 // Keep going if we are hitting this case.
7872 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()) &&
7873 (VT != MVT::v8f16 || ST->hasFullFP16()))
7874 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7875
7876 unsigned EltSize = VT.getScalarSizeInBits();
7877
7878 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
7879 // i32 and try again.
7880 if (hasDominantValue && EltSize <= 32) {
7881 if (!isConstant) {
7882 SDValue N;
7883
7884 // If we are VDUPing a value that comes directly from a vector, that will
7885 // cause an unnecessary move to and from a GPR, where instead we could
7886 // just use VDUPLANE. We can only do this if the lane being extracted
7887 // is at a constant index, as the VDUP from lane instructions only have
7888 // constant-index forms.
7889 ConstantSDNode *constIndex;
7890 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7891 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
7892 // We need to create a new undef vector to use for the VDUPLANE if the
7893 // size of the vector from which we get the value is different than the
7894 // size of the vector that we need to create. We will insert the element
7895 // such that the register coalescer will remove unnecessary copies.
7896 if (VT != Value->getOperand(0).getValueType()) {
7897 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7899 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7900 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
7901 Value, DAG.getConstant(index, dl, MVT::i32)),
7902 DAG.getConstant(index, dl, MVT::i32));
7903 } else
7904 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7905 Value->getOperand(0), Value->getOperand(1));
7906 } else
7907 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
7908
7909 if (!usesOnlyOneValue) {
7910 // The dominant value was splatted as 'N', but we now have to insert
7911 // all differing elements.
7912 for (unsigned I = 0; I < NumElts; ++I) {
7913 if (Op.getOperand(I) == Value)
7914 continue;
7916 Ops.push_back(N);
7917 Ops.push_back(Op.getOperand(I));
7918 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
7919 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
7920 }
7921 }
7922 return N;
7923 }
7926 MVT FVT = VT.getVectorElementType().getSimpleVT();
7927 assert(FVT == MVT::f32 || FVT == MVT::f16);
7928 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7929 for (unsigned i = 0; i < NumElts; ++i)
7930 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
7931 Op.getOperand(i)));
7932 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
7933 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7934 Val = LowerBUILD_VECTOR(Val, DAG, ST);
7935 if (Val.getNode())
7936 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7937 }
7938 if (usesOnlyOneValue) {
7939 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
7940 if (isConstant && Val.getNode())
7941 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
7942 }
7943 }
7944
7945 // If all elements are constants and the case above didn't get hit, fall back
7946 // to the default expansion, which will generate a load from the constant
7947 // pool.
7948 if (isConstant)
7949 return SDValue();
7950
7951 // Reconstruct the BUILDVECTOR to one of the legal shuffles (such as vext and
7952 // vmovn). Empirical tests suggest this is rarely worth it for vectors of
7953 // length <= 2.
7954 if (NumElts >= 4)
7955 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
7956 return shuffle;
7957
7958 // Attempt to turn a buildvector of scalar fptrunc's or fpext's back into
7959 // VCVT's
7960 if (SDValue VCVT = LowerBuildVectorOfFPTrunc(Op, DAG, Subtarget))
7961 return VCVT;
7962 if (SDValue VCVT = LowerBuildVectorOfFPExt(Op, DAG, Subtarget))
7963 return VCVT;
7964
7965 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7966 // If we haven't found an efficient lowering, try splitting a 128-bit vector
7967 // into two 64-bit vectors; we might discover a better way to lower it.
7968 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7969 EVT ExtVT = VT.getVectorElementType();
7970 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
7971 SDValue Lower = DAG.getBuildVector(HVT, dl, ArrayRef(&Ops[0], NumElts / 2));
7972 if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7973 Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
7974 SDValue Upper =
7975 DAG.getBuildVector(HVT, dl, ArrayRef(&Ops[NumElts / 2], NumElts / 2));
7976 if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7977 Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
7978 if (Lower && Upper)
7979 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
7980 }
7981
7982 // Vectors with 32- or 64-bit elements can be built by directly assigning
7983 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
7984 // will be legalized.
7985 if (EltSize >= 32) {
7986 // Do the expansion with floating-point types, since that is what the VFP
7987 // registers are defined to use, and since i64 is not legal.
7988 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7989 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7991 for (unsigned i = 0; i < NumElts; ++i)
7992 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
7993 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7994 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7995 }
7996
7997 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7998 // know the default expansion would otherwise fall back on something even
7999 // worse. For a vector with one or two non-undef values, that's
8000 // scalar_to_vector for the elements followed by a shuffle (provided the
8001 // shuffle is valid for the target) and materialization element by element
8002 // on the stack followed by a load for everything else.
8003 if ((!isConstant && !usesOnlyOneValue) ||
8004 (VT == MVT::v8f16 && !ST->hasFullFP16())) {
8005 SDValue Vec = DAG.getUNDEF(VT);
8006 for (unsigned i = 0 ; i < NumElts; ++i) {
8007 SDValue V = Op.getOperand(i);
8008 if (V.isUndef())
8009 continue;
8010 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
8011 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
8012 }
8013 return Vec;
8014 }
8015
8016 return SDValue();
8017}
8018
8019// Gather data to see if the operation can be modelled as a
8020// shuffle in combination with VEXTs.
8021SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
8022 SelectionDAG &DAG) const {
8023 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
8024 SDLoc dl(Op);
8025 EVT VT = Op.getValueType();
8026 unsigned NumElts = VT.getVectorNumElements();
8027
8028 struct ShuffleSourceInfo {
8029 SDValue Vec;
8030 unsigned MinElt = std::numeric_limits<unsigned>::max();
8031 unsigned MaxElt = 0;
8032
8033 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to