LLVM 24.0.0git
MipsISelLowering.cpp
Go to the documentation of this file.
1//===- MipsISelLowering.cpp - Mips 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 Mips uses to lower LLVM code into a
10// selection DAG.
11//
12//===----------------------------------------------------------------------===//
13
14#include "MipsISelLowering.h"
18#include "MipsCCState.h"
19#include "MipsInstrInfo.h"
20#include "MipsMachineFunction.h"
21#include "MipsRegisterInfo.h"
22#include "MipsSubtarget.h"
23#include "MipsTargetMachine.h"
25#include "llvm/ADT/APFloat.h"
26#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/StringRef.h"
49#include "llvm/IR/CallingConv.h"
50#include "llvm/IR/Constants.h"
51#include "llvm/IR/DataLayout.h"
52#include "llvm/IR/DebugLoc.h"
54#include "llvm/IR/Function.h"
55#include "llvm/IR/GlobalValue.h"
56#include "llvm/IR/Module.h"
57#include "llvm/IR/Type.h"
58#include "llvm/IR/Value.h"
59#include "llvm/MC/MCContext.h"
68#include <algorithm>
69#include <cassert>
70#include <cctype>
71#include <cstdint>
72#include <deque>
73#include <iterator>
74#include <string>
75#include <utility>
76#include <vector>
77
78using namespace llvm;
79
80#define DEBUG_TYPE "mips-lower"
81
82STATISTIC(NumTailCalls, "Number of tail calls");
83
86
87static cl::opt<bool> UseMipsTailCalls("mips-tail-calls", cl::Hidden,
88 cl::desc("MIPS: permit tail calls."),
89 cl::init(false));
90
91static const MCPhysReg Mips64DPRegs[8] = {
92 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
93 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
94};
95
97 Break, // MIPS I
98 Teq, // MIPS II+
99 TeqMM, // microMIPS
100};
101
102// The MIPS MSA ABI passes vector arguments in the integer register set.
103// The number of integer registers used is dependant on the ABI used.
106 EVT VT) const {
107 if (!VT.isVector())
108 return getRegisterType(Context, VT);
109
111 return Subtarget.isABI_O32() || VT.getSizeInBits() == 32 ? MVT::i32
112 : MVT::i64;
113 return getRegisterType(Context, VT.getVectorElementType());
114}
115
118 EVT VT) const {
119 if (VT.isVector()) {
121 return divideCeil(VT.getSizeInBits(), Subtarget.isABI_O32() ? 32 : 64);
122 return VT.getVectorNumElements() *
124 }
125 return MipsTargetLowering::getNumRegisters(Context, VT);
126}
127
129 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
130 unsigned &NumIntermediates, MVT &RegisterVT) const {
131 if (VT.isPow2VectorType() && VT.getVectorElementType().isRound()) {
132 IntermediateVT = getRegisterTypeForCallingConv(Context, CC, VT);
133 RegisterVT = IntermediateVT.getSimpleVT();
134 NumIntermediates = getNumRegistersForCallingConv(Context, CC, VT);
135 return NumIntermediates;
136 }
137 IntermediateVT = VT.getVectorElementType();
138 NumIntermediates = VT.getVectorNumElements();
139 RegisterVT = getRegisterType(Context, IntermediateVT);
140 return NumIntermediates * getNumRegisters(Context, IntermediateVT);
141}
142
148
149SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
150 SelectionDAG &DAG,
151 unsigned Flag) const {
152 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
153}
154
155SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
156 SelectionDAG &DAG,
157 unsigned Flag) const {
158 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
159}
160
161SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
162 SelectionDAG &DAG,
163 unsigned Flag) const {
164 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
165}
166
167SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
168 SelectionDAG &DAG,
169 unsigned Flag) const {
170 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
171}
172
173SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
174 SelectionDAG &DAG,
175 unsigned Flag) const {
176 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
177 N->getOffset(), Flag);
178}
179
181 const MipsSubtarget &STI)
182 : TargetLowering(TM, STI), Subtarget(STI), ABI(STI.getABI()) {
183 // Mips does not have i1 type, so use i32 for
184 // setcc operations results (slt, sgt, ...).
187 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
188 // does. Integer booleans still use 0 and 1.
189 if (Subtarget.hasMips32r6())
192
193 // Load extented operations for i1 types must be promoted
194 for (MVT VT : MVT::integer_valuetypes()) {
198 }
199
200 // MIPS doesn't have extending float->double load/store. Set LoadExtAction
201 // for f32, f16
202 for (MVT VT : MVT::fp_valuetypes()) {
203 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
204 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
205 }
206
207 // Set LoadExtAction for f16 vectors to Expand
209 MVT F16VT = MVT::getVectorVT(MVT::f16, VT.getVectorNumElements());
210 if (F16VT.isValid())
212 }
213
214 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
215 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
216
217 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
218
219 // Used by legalize types to correctly generate the setcc result.
220 // Without this, every float setcc comes with a AND/OR with the result,
221 // we don't want this, since the fpcmp result goes to a flag register,
222 // which is used implicitly by brcond and select operations.
223 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
224
225 // Mips Custom Operations
231 if (!Subtarget.inMips16Mode())
246
251
252 if (Subtarget.hasMips32r2() ||
253 getTargetMachine().getTargetTriple().isOSLinux())
255
256 // Lower fmin/fmax/fclass operations for MIPS R6.
257 if (Subtarget.hasMips32r6()) {
270 } else {
273 }
274
275 if (Subtarget.hasMTHC1())
277
278 if (Subtarget.isGP64bit()) {
283 if (!Subtarget.inMips16Mode())
286 if (Subtarget.hasMips64r6()) {
289 } else {
292 }
299 }
300
301 if (!Subtarget.isGP64bit()) {
305 }
306
308 if (Subtarget.isGP64bit())
310
319
320 // Operations not directly supported by Mips.
334
335 if (Subtarget.hasCnMips()) {
338 } else {
341 }
348
349 if (!Subtarget.hasMips32r2())
351
352 if (!Subtarget.hasMips64r2())
354
371
372 // Lower f16 conversion operations into library calls
377
379
384
385 // Use the default for now
388
389 if (!Subtarget.isGP64bit()) {
392 }
393
394 if (!Subtarget.hasMips32r2()) {
397 }
398
399 // MIPS16 lacks MIPS32's clz and clo instructions.
400 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
402 if (!Subtarget.hasMips64())
404
405 if (!Subtarget.hasMips32r2())
407 if (!Subtarget.hasMips64r2())
409
410 if (Subtarget.isGP64bit() && Subtarget.hasMips64r6()) {
411 setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Legal);
412 setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Legal);
413 setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Legal);
414 setTruncStoreAction(MVT::i64, MVT::i32, Legal);
415 } else if (Subtarget.isGP64bit()) {
416 setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Custom);
417 setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Custom);
418 setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Custom);
419 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
420 }
421
422 setOperationAction(ISD::TRAP, MVT::Other, Legal);
423
427
428 // Sink shifts into their users' blocks to expose extract patterns.
429 setHasExtractBitsInsn(Subtarget.hasExtractInsert());
430
431 // R5900 has no LL/SC instructions for atomic operations
432 if (Subtarget.isR5900())
434 else if (Subtarget.isGP64bit())
436 else
438
439 setMinFunctionAlignment(Subtarget.isGP64bit() ? Align(8) : Align(4));
440
441 // The arguments on the stack are defined in terms of 4-byte slots on O32
442 // and 8-byte slots on N32/N64.
443 setMinStackArgumentAlignment((ABI.IsN32() || ABI.IsN64()) ? Align(8)
444 : Align(4));
445
446 setStackPointerRegisterToSaveRestore(ABI.IsN64() ? Mips::SP_64 : Mips::SP);
447
449
450 isMicroMips = Subtarget.inMicroMipsMode();
451}
452
453const MipsTargetLowering *
455 const MipsSubtarget &STI) {
456 if (STI.inMips16Mode())
457 return createMips16TargetLowering(TM, STI);
458
459 return createMipsSETargetLowering(TM, STI);
460}
461
462// Create a fast isel object.
464 FunctionLoweringInfo &funcInfo, const TargetLibraryInfo *libInfo,
465 const LibcallLoweringInfo *libcallLowering) const {
466 const MipsTargetMachine &TM =
467 static_cast<const MipsTargetMachine &>(funcInfo.MF->getTarget());
468
469 // We support only the standard encoding [MIPS32,MIPS32R5] ISAs.
470 bool UseFastISel = TM.Options.EnableFastISel && Subtarget.hasMips32() &&
471 !Subtarget.hasMips32r6() && !Subtarget.inMips16Mode() &&
472 !Subtarget.inMicroMipsMode();
473
474 // Disable if either of the following is true:
475 // We do not generate PIC, the ABI is not O32, XGOT is being used.
476 if (!TM.isPositionIndependent() || !Subtarget.getABI().IsO32() ||
477 Subtarget.useXGOT())
478 UseFastISel = false;
479
480 return UseFastISel ? Mips::createFastISel(funcInfo, libInfo, libcallLowering)
481 : nullptr;
482}
483
485 EVT VT) const {
486 if (!VT.isVector())
487 return MVT::i32;
489}
490
493 const MipsSubtarget &Subtarget) {
494 if (DCI.isBeforeLegalizeOps())
495 return SDValue();
496
497 EVT Ty = N->getValueType(0);
498 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
499 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
500 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
501 MipsISD::DivRemU16;
502 SDLoc DL(N);
503
504 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
505 N->getOperand(0), N->getOperand(1));
506 SDValue InChain = DAG.getEntryNode();
507 SDValue InGlue = DivRem;
508
509 // insert MFLO
510 if (N->hasAnyUseOfValue(0)) {
511 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
512 InGlue);
513 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
514 InChain = CopyFromLo.getValue(1);
515 InGlue = CopyFromLo.getValue(2);
516 }
517
518 // insert MFHI
519 if (N->hasAnyUseOfValue(1)) {
520 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
521 HI, Ty, InGlue);
522 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
523 }
524
525 return SDValue();
526}
527
529 switch (CC) {
530 default: llvm_unreachable("Unknown fp condition code!");
531 case ISD::SETEQ:
532 case ISD::SETOEQ: return Mips::FCOND_OEQ;
533 case ISD::SETUNE: return Mips::FCOND_UNE;
534 case ISD::SETLT:
535 case ISD::SETOLT: return Mips::FCOND_OLT;
536 case ISD::SETGT:
537 case ISD::SETOGT: return Mips::FCOND_OGT;
538 case ISD::SETLE:
539 case ISD::SETOLE: return Mips::FCOND_OLE;
540 case ISD::SETGE:
541 case ISD::SETOGE: return Mips::FCOND_OGE;
542 case ISD::SETULT: return Mips::FCOND_ULT;
543 case ISD::SETULE: return Mips::FCOND_ULE;
544 case ISD::SETUGT: return Mips::FCOND_UGT;
545 case ISD::SETUGE: return Mips::FCOND_UGE;
546 case ISD::SETUO: return Mips::FCOND_UN;
547 case ISD::SETO: return Mips::FCOND_OR;
548 case ISD::SETNE:
549 case ISD::SETONE: return Mips::FCOND_ONE;
550 case ISD::SETUEQ: return Mips::FCOND_UEQ;
551 }
552}
553
554/// This function returns true if the floating point conditional branches and
555/// conditional moves which use condition code CC should be inverted.
557 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
558 return false;
559
560 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
561 "Illegal Condition Code");
562
563 return true;
564}
565
566// Creates and returns an FPCmp node from a setcc node.
567// Returns Op if setcc is not a floating point comparison.
569 // must be a SETCC node
570 if (Op.getOpcode() != ISD::SETCC && Op.getOpcode() != ISD::STRICT_FSETCC &&
571 Op.getOpcode() != ISD::STRICT_FSETCCS)
572 return Op;
573
574 SDValue LHS = Op.getOperand(0);
575
576 if (!LHS.getValueType().isFloatingPoint())
577 return Op;
578
579 SDValue RHS = Op.getOperand(1);
580 SDLoc DL(Op);
581
582 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
583 // node if necessary.
584 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
585
586 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
587 DAG.getConstant(condCodeToFCC(CC), DL, MVT::i32));
588}
589
590// Creates and returns a CMovFPT/F node.
592 SDValue False, const SDLoc &DL) {
593 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
595 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
596
597 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
598 True.getValueType(), True, FCC0, False, Cond);
599}
600
603 const MipsSubtarget &Subtarget) {
604 if (DCI.isBeforeLegalizeOps())
605 return SDValue();
606
607 SDValue SetCC = N->getOperand(0);
608
609 if ((SetCC.getOpcode() != ISD::SETCC) ||
610 !SetCC.getOperand(0).getValueType().isInteger())
611 return SDValue();
612
613 SDValue False = N->getOperand(2);
614 EVT FalseTy = False.getValueType();
615
616 if (!FalseTy.isInteger())
617 return SDValue();
618
620
621 // If the RHS (False) is 0, we swap the order of the operands
622 // of ISD::SELECT (obviously also inverting the condition) so that we can
623 // take advantage of conditional moves using the $0 register.
624 // Example:
625 // return (a != 0) ? x : 0;
626 // load $reg, x
627 // movz $reg, $0, a
628 if (!FalseC)
629 return SDValue();
630
631 const SDLoc DL(N);
632
633 if (!FalseC->getZExtValue()) {
634 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
635 SDValue True = N->getOperand(1);
636
637 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
638 SetCC.getOperand(1),
640
641 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
642 }
643
644 // If both operands are integer constants there's a possibility that we
645 // can do some interesting optimizations.
646 SDValue True = N->getOperand(1);
648
649 if (!TrueC || !True.getValueType().isInteger())
650 return SDValue();
651
652 // We'll also ignore MVT::i64 operands as this optimizations proves
653 // to be ineffective because of the required sign extensions as the result
654 // of a SETCC operator is always MVT::i32 for non-vector types.
655 if (True.getValueType() == MVT::i64)
656 return SDValue();
657
658 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
659
660 // 1) (a < x) ? y : y-1
661 // slti $reg1, a, x
662 // addiu $reg2, $reg1, y-1
663 if (Diff == 1)
664 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
665
666 // 2) (a < x) ? y-1 : y
667 // slti $reg1, a, x
668 // xor $reg1, $reg1, 1
669 // addiu $reg2, $reg1, y-1
670 if (Diff == -1) {
671 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
672 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
673 SetCC.getOperand(1),
675 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
676 }
677
678 // Could not optimize.
679 return SDValue();
680}
681
684 const MipsSubtarget &Subtarget) {
685 if (DCI.isBeforeLegalizeOps())
686 return SDValue();
687
688 SDValue ValueIfTrue = N->getOperand(0), ValueIfFalse = N->getOperand(2);
689
690 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(ValueIfFalse);
691 if (!FalseC || FalseC->getZExtValue())
692 return SDValue();
693
694 // Since RHS (False) is 0, we swap the order of the True/False operands
695 // (obviously also inverting the condition) so that we can
696 // take advantage of conditional moves using the $0 register.
697 // Example:
698 // return (a != 0) ? x : 0;
699 // load $reg, x
700 // movz $reg, $0, a
701 unsigned Opc = (N->getOpcode() == MipsISD::CMovFP_T) ? MipsISD::CMovFP_F :
702 MipsISD::CMovFP_T;
703
704 SDValue FCC = N->getOperand(1), Glue = N->getOperand(3);
705 return DAG.getNode(Opc, SDLoc(N), ValueIfFalse.getValueType(),
706 ValueIfFalse, FCC, ValueIfTrue, Glue);
707}
708
711 const MipsSubtarget &Subtarget) {
712 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
713 return SDValue();
714
715 SDValue FirstOperand = N->getOperand(0);
716 unsigned FirstOperandOpc = FirstOperand.getOpcode();
717 SDValue Mask = N->getOperand(1);
718 EVT ValTy = N->getValueType(0);
719 SDLoc DL(N);
720
721 uint64_t Pos = 0;
722 unsigned SMPos, SMSize;
723 ConstantSDNode *CN;
724 SDValue NewOperand;
725 unsigned Opc;
726
727 // Op's second operand must be a shifted mask.
728 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
729 !isShiftedMask_64(CN->getZExtValue(), SMPos, SMSize))
730 return SDValue();
731
732 if (FirstOperandOpc == ISD::SRA || FirstOperandOpc == ISD::SRL) {
733 // Pattern match EXT.
734 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
735 // => ext $dst, $src, pos, size
736
737 // The second operand of the shift must be an immediate.
738 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
739 return SDValue();
740
741 Pos = CN->getZExtValue();
742
743 // Return if the shifted mask does not start at bit 0 or the sum of its size
744 // and Pos exceeds the word's size.
745 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
746 return SDValue();
747
748 Opc = MipsISD::Ext;
749 NewOperand = FirstOperand.getOperand(0);
750 } else if (FirstOperandOpc == ISD::SHL && Subtarget.hasCnMips()) {
751 // Pattern match CINS.
752 // $dst = and (shl $src , pos), mask
753 // => cins $dst, $src, pos, size
754 // mask is a shifted mask with consecutive 1's, pos = shift amount,
755 // size = population count.
756
757 // The second operand of the shift must be an immediate.
758 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
759 return SDValue();
760
761 Pos = CN->getZExtValue();
762
763 if (SMPos != Pos || Pos >= ValTy.getSizeInBits() || SMSize >= 32 ||
764 Pos + SMSize > ValTy.getSizeInBits())
765 return SDValue();
766
767 NewOperand = FirstOperand.getOperand(0);
768 // SMSize is 'location' (position) in this case, not size.
769 SMSize--;
770 Opc = MipsISD::CIns;
771 } else {
772 // Pattern match EXT.
773 // $dst = and $src, (2**size - 1) , if size > 16
774 // => ext $dst, $src, pos, size , pos = 0
775
776 // If the mask is <= 0xffff, andi can be used instead.
777 if (CN->getZExtValue() <= 0xffff)
778 return SDValue();
779
780 // Return if the mask doesn't start at position 0.
781 if (SMPos)
782 return SDValue();
783
784 Opc = MipsISD::Ext;
785 NewOperand = FirstOperand;
786 }
787 return DAG.getNode(Opc, DL, ValTy, NewOperand,
788 DAG.getConstant(Pos, DL, MVT::i32),
789 DAG.getConstant(SMSize, DL, MVT::i32));
790}
791
794 const MipsSubtarget &Subtarget) {
795 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
796 return SDValue();
797
798 SDValue FirstOperand = N->getOperand(0), SecondOperand = N->getOperand(1);
799 unsigned SMPos0, SMSize0, SMPos1, SMSize1;
800 ConstantSDNode *CN, *CN1;
801
802 if ((FirstOperand.getOpcode() == ISD::AND &&
803 SecondOperand.getOpcode() == ISD::SHL) ||
804 (FirstOperand.getOpcode() == ISD::SHL &&
805 SecondOperand.getOpcode() == ISD::AND)) {
806 // Pattern match INS.
807 // $dst = or (and $src1, (2**size0 - 1)), (shl $src2, size0)
808 // ==> ins $src1, $src2, pos, size, pos = size0, size = 32 - pos;
809 // Or:
810 // $dst = or (shl $src2, size0), (and $src1, (2**size0 - 1))
811 // ==> ins $src1, $src2, pos, size, pos = size0, size = 32 - pos;
812 SDValue AndOperand0 = FirstOperand.getOpcode() == ISD::AND
813 ? FirstOperand.getOperand(0)
814 : SecondOperand.getOperand(0);
815 SDValue ShlOperand0 = FirstOperand.getOpcode() == ISD::AND
816 ? SecondOperand.getOperand(0)
817 : FirstOperand.getOperand(0);
818 SDValue AndMask = FirstOperand.getOpcode() == ISD::AND
819 ? FirstOperand.getOperand(1)
820 : SecondOperand.getOperand(1);
821 if (!(CN = dyn_cast<ConstantSDNode>(AndMask)) ||
822 !isShiftedMask_64(CN->getZExtValue(), SMPos0, SMSize0))
823 return SDValue();
824
825 SDValue ShlShift = FirstOperand.getOpcode() == ISD::AND
826 ? SecondOperand.getOperand(1)
827 : FirstOperand.getOperand(1);
828 if (!(CN = dyn_cast<ConstantSDNode>(ShlShift)))
829 return SDValue();
830 uint64_t ShlShiftValue = CN->getZExtValue();
831
832 if (SMPos0 != 0 || SMSize0 != ShlShiftValue)
833 return SDValue();
834
835 SDLoc DL(N);
836 EVT ValTy = N->getValueType(0);
837 SMPos1 = ShlShiftValue;
838 assert(SMPos1 < ValTy.getSizeInBits());
839 SMSize1 = (ValTy == MVT::i64 ? 64 : 32) - SMPos1;
840 return DAG.getNode(MipsISD::Ins, DL, ValTy, ShlOperand0,
841 DAG.getConstant(SMPos1, DL, MVT::i32),
842 DAG.getConstant(SMSize1, DL, MVT::i32), AndOperand0);
843 }
844
845 // See if Op's first operand matches (and $src1 , mask0).
846 if (FirstOperand.getOpcode() != ISD::AND)
847 return SDValue();
848
849 // Pattern match INS.
850 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
851 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
852 // => ins $dst, $src, size, pos, $src1
853 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))) ||
854 !isShiftedMask_64(~CN->getSExtValue(), SMPos0, SMSize0))
855 return SDValue();
856
857 // See if Op's second operand matches (and (shl $src, pos), mask1).
858 if (SecondOperand.getOpcode() == ISD::AND &&
859 SecondOperand.getOperand(0).getOpcode() == ISD::SHL) {
860
861 if (!(CN = dyn_cast<ConstantSDNode>(SecondOperand.getOperand(1))) ||
862 !isShiftedMask_64(CN->getZExtValue(), SMPos1, SMSize1))
863 return SDValue();
864
865 // The shift masks must have the same position and size.
866 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
867 return SDValue();
868
869 SDValue Shl = SecondOperand.getOperand(0);
870
871 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
872 return SDValue();
873
874 unsigned Shamt = CN->getZExtValue();
875
876 // Return if the shift amount and the first bit position of mask are not the
877 // same.
878 EVT ValTy = N->getValueType(0);
879 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
880 return SDValue();
881
882 SDLoc DL(N);
883 return DAG.getNode(MipsISD::Ins, DL, ValTy, Shl.getOperand(0),
884 DAG.getConstant(SMPos0, DL, MVT::i32),
885 DAG.getConstant(SMSize0, DL, MVT::i32),
886 FirstOperand.getOperand(0));
887 } else {
888 // Pattern match DINS.
889 // $dst = or (and $src, mask0), mask1
890 // where mask0 = maskTrailingOnes<uint64_t>(SMSize0) << SMPos0
891 // => dins $dst, $src, pos, size
892 uint64_t Mask = maskTrailingOnes<uint64_t>(SMSize0) << SMPos0;
893 if (~CN->getSExtValue() == (int64_t)Mask &&
894 ((SMSize0 + SMPos0 <= 64 && Subtarget.hasMips64r2()) ||
895 (SMSize0 + SMPos0 <= 32))) {
896 // Check if AND instruction has constant as argument
897 bool isConstCase = SecondOperand.getOpcode() != ISD::AND;
898 if (SecondOperand.getOpcode() == ISD::AND) {
899 if (!(CN1 = dyn_cast<ConstantSDNode>(SecondOperand->getOperand(1))))
900 return SDValue();
901 } else {
902 if (!(CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1))))
903 return SDValue();
904 }
905 // Don't generate INS if constant OR operand doesn't fit into bits
906 // cleared by constant AND operand.
907 if (CN->getSExtValue() & CN1->getSExtValue())
908 return SDValue();
909
910 SDLoc DL(N);
911 EVT ValTy = N->getOperand(0)->getValueType(0);
912 SDValue Const1;
913 SDValue SrlX;
914 if (!isConstCase) {
915 Const1 = DAG.getConstant(SMPos0, DL, MVT::i32);
916 SrlX = DAG.getNode(ISD::SRL, DL, SecondOperand->getValueType(0),
917 SecondOperand, Const1);
918 }
919 return DAG.getNode(
920 MipsISD::Ins, DL, N->getValueType(0),
921 isConstCase
922 ? DAG.getSignedConstant(CN1->getSExtValue() >> SMPos0, DL, ValTy)
923 : SrlX,
924 DAG.getConstant(SMPos0, DL, MVT::i32),
925 DAG.getConstant(ValTy.getSizeInBits() / 8 < 8 ? SMSize0 & 31
926 : SMSize0,
927 DL, MVT::i32),
928 FirstOperand->getOperand(0));
929 }
930 return SDValue();
931 }
932}
933
935 const MipsSubtarget &Subtarget) {
936 // ROOTNode must have a multiplication as an operand for the match to be
937 // successful.
938 if (ROOTNode->getOperand(0).getOpcode() != ISD::MUL &&
939 ROOTNode->getOperand(1).getOpcode() != ISD::MUL)
940 return SDValue();
941
942 // In the case where we have a multiplication as the left operand of
943 // of a subtraction, we can't combine into a MipsISD::MSub node as the
944 // the instruction definition of msub(u) places the multiplication on
945 // on the right.
946 if (ROOTNode->getOpcode() == ISD::SUB &&
947 ROOTNode->getOperand(0).getOpcode() == ISD::MUL)
948 return SDValue();
949
950 // We don't handle vector types here.
951 if (ROOTNode->getValueType(0).isVector())
952 return SDValue();
953
954 // For MIPS64, madd / msub instructions are inefficent to use with 64 bit
955 // arithmetic. E.g.
956 // (add (mul a b) c) =>
957 // let res = (madd (mthi (drotr c 32))x(mtlo c) a b) in
958 // MIPS64: (or (dsll (mfhi res) 32) (dsrl (dsll (mflo res) 32) 32)
959 // or
960 // MIPS64R2: (dins (mflo res) (mfhi res) 32 32)
961 //
962 // The overhead of setting up the Hi/Lo registers and reassembling the
963 // result makes this a dubious optimzation for MIPS64. The core of the
964 // problem is that Hi/Lo contain the upper and lower 32 bits of the
965 // operand and result.
966 //
967 // It requires a chain of 4 add/mul for MIPS64R2 to get better code
968 // density than doing it naively, 5 for MIPS64. Additionally, using
969 // madd/msub on MIPS64 requires the operands actually be 32 bit sign
970 // extended operands, not true 64 bit values.
971 //
972 // FIXME: For the moment, disable this completely for MIPS64.
973 if (Subtarget.hasMips64())
974 return SDValue();
975
976 SDValue Mult = ROOTNode->getOperand(0).getOpcode() == ISD::MUL
977 ? ROOTNode->getOperand(0)
978 : ROOTNode->getOperand(1);
979
980 SDValue AddOperand = ROOTNode->getOperand(0).getOpcode() == ISD::MUL
981 ? ROOTNode->getOperand(1)
982 : ROOTNode->getOperand(0);
983
984 // Transform this to a MADD only if the user of this node is the add.
985 // If there are other users of the mul, this function returns here.
986 if (!Mult.hasOneUse())
987 return SDValue();
988
989 // maddu and madd are unusual instructions in that on MIPS64 bits 63..31
990 // must be in canonical form, i.e. sign extended. For MIPS32, the operands
991 // of the multiply must have 32 or more sign bits, otherwise we cannot
992 // perform this optimization. We have to check this here as we're performing
993 // this optimization pre-legalization.
994 SDValue MultLHS = Mult->getOperand(0);
995 SDValue MultRHS = Mult->getOperand(1);
996
997 bool IsSigned = MultLHS->getOpcode() == ISD::SIGN_EXTEND &&
998 MultRHS->getOpcode() == ISD::SIGN_EXTEND;
999 bool IsUnsigned = MultLHS->getOpcode() == ISD::ZERO_EXTEND &&
1000 MultRHS->getOpcode() == ISD::ZERO_EXTEND;
1001
1002 if (!IsSigned && !IsUnsigned)
1003 return SDValue();
1004
1005 // Initialize accumulator.
1006 SDLoc DL(ROOTNode);
1007 SDValue BottomHalf, TopHalf;
1008 std::tie(BottomHalf, TopHalf) =
1009 CurDAG.SplitScalar(AddOperand, DL, MVT::i32, MVT::i32);
1010 SDValue ACCIn =
1011 CurDAG.getNode(MipsISD::MTLOHI, DL, MVT::Untyped, BottomHalf, TopHalf);
1012
1013 // Create MipsMAdd(u) / MipsMSub(u) node.
1014 bool IsAdd = ROOTNode->getOpcode() == ISD::ADD;
1015 unsigned Opcode = IsAdd ? (IsUnsigned ? MipsISD::MAddu : MipsISD::MAdd)
1016 : (IsUnsigned ? MipsISD::MSubu : MipsISD::MSub);
1017 SDValue MAddOps[3] = {
1018 CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(0)),
1019 CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(1)), ACCIn};
1020 SDValue MAdd = CurDAG.getNode(Opcode, DL, MVT::Untyped, MAddOps);
1021
1022 SDValue ResLo = CurDAG.getNode(MipsISD::MFLO, DL, MVT::i32, MAdd);
1023 SDValue ResHi = CurDAG.getNode(MipsISD::MFHI, DL, MVT::i32, MAdd);
1024 SDValue Combined =
1025 CurDAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResLo, ResHi);
1026 return Combined;
1027}
1028
1031 const MipsSubtarget &Subtarget) {
1032 // (sub v0 (mul v1, v2)) => (msub v1, v2, v0)
1033 if (DCI.isBeforeLegalizeOps()) {
1034 if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() &&
1035 !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64)
1036 return performMADD_MSUBCombine(N, DAG, Subtarget);
1037
1038 return SDValue();
1039 }
1040
1041 return SDValue();
1042}
1043
1046 const MipsSubtarget &Subtarget) {
1047 // (add v0 (mul v1, v2)) => (madd v1, v2, v0)
1048 if (DCI.isBeforeLegalizeOps()) {
1049 if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() &&
1050 !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64)
1051 return performMADD_MSUBCombine(N, DAG, Subtarget);
1052
1053 return SDValue();
1054 }
1055
1056 // When loading from a jump table, push the Lo node to the position that
1057 // allows folding it into a load immediate.
1058 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
1059 // (add (add abs_lo(tjt), v1), v0) => (add (add v0, v1), abs_lo(tjt))
1060 SDValue InnerAdd = N->getOperand(1);
1061 SDValue Index = N->getOperand(0);
1062 if (InnerAdd.getOpcode() != ISD::ADD)
1063 std::swap(InnerAdd, Index);
1064 if (InnerAdd.getOpcode() != ISD::ADD)
1065 return SDValue();
1066
1067 SDValue Lo = InnerAdd.getOperand(0);
1068 SDValue Other = InnerAdd.getOperand(1);
1069 if (Lo.getOpcode() != MipsISD::Lo)
1070 std::swap(Lo, Other);
1071
1072 if ((Lo.getOpcode() != MipsISD::Lo) ||
1073 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
1074 return SDValue();
1075
1076 EVT ValTy = N->getValueType(0);
1077 SDLoc DL(N);
1078
1079 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, Index, Other);
1080 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
1081}
1082
1085 const MipsSubtarget &Subtarget) {
1086 // Pattern match CINS.
1087 // $dst = shl (and $src , imm), pos
1088 // => cins $dst, $src, pos, size
1089
1090 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasCnMips())
1091 return SDValue();
1092
1093 SDValue FirstOperand = N->getOperand(0);
1094 unsigned FirstOperandOpc = FirstOperand.getOpcode();
1095 SDValue SecondOperand = N->getOperand(1);
1096 EVT ValTy = N->getValueType(0);
1097 SDLoc DL(N);
1098
1099 uint64_t Pos = 0;
1100 unsigned SMPos, SMSize;
1101 ConstantSDNode *CN;
1102 SDValue NewOperand;
1103
1104 // The second operand of the shift must be an immediate.
1105 if (!(CN = dyn_cast<ConstantSDNode>(SecondOperand)))
1106 return SDValue();
1107
1108 Pos = CN->getZExtValue();
1109
1110 if (Pos >= ValTy.getSizeInBits())
1111 return SDValue();
1112
1113 if (FirstOperandOpc != ISD::AND)
1114 return SDValue();
1115
1116 // AND's second operand must be a shifted mask.
1117 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))) ||
1118 !isShiftedMask_64(CN->getZExtValue(), SMPos, SMSize))
1119 return SDValue();
1120
1121 // Return if the shifted mask does not start at bit 0 or the sum of its size
1122 // and Pos exceeds the word's size.
1123 if (SMPos != 0 || SMSize > 32 || Pos + SMSize > ValTy.getSizeInBits())
1124 return SDValue();
1125
1126 NewOperand = FirstOperand.getOperand(0);
1127 // SMSize is 'location' (position) in this case, not size.
1128 SMSize--;
1129
1130 return DAG.getNode(MipsISD::CIns, DL, ValTy, NewOperand,
1131 DAG.getConstant(Pos, DL, MVT::i32),
1132 DAG.getConstant(SMSize, DL, MVT::i32));
1133}
1134
1137 const MipsSubtarget &Subtarget) {
1138 if (DCI.Level != AfterLegalizeDAG || !Subtarget.isGP64bit()) {
1139 return SDValue();
1140 }
1141
1142 SDValue N0 = N->getOperand(0);
1143 EVT VT = N->getValueType(0);
1144
1145 // Pattern match XOR.
1146 // $dst = sign_extend (xor (trunc $src, i32), imm)
1147 // => $dst = xor (signext_inreg $src, i32), imm
1148 if (N0.getOpcode() == ISD::XOR &&
1149 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
1150 N0.getOperand(1).getOpcode() == ISD::Constant) {
1151 SDValue TruncateSource = N0.getOperand(0).getOperand(0);
1152 auto *ConstantOperand = dyn_cast<ConstantSDNode>(N0->getOperand(1));
1153
1154 SDValue FirstOperand =
1155 DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N0), VT, TruncateSource,
1156 DAG.getValueType(N0.getOperand(0).getValueType()));
1157
1158 int64_t ConstImm = ConstantOperand->getSExtValue();
1159 return DAG.getNode(ISD::XOR, SDLoc(N0), VT, FirstOperand,
1160 DAG.getConstant(ConstImm, SDLoc(N0), VT));
1161 }
1162
1163 return SDValue();
1164}
1165
1167 const {
1168 SelectionDAG &DAG = DCI.DAG;
1169 unsigned Opc = N->getOpcode();
1170
1171 switch (Opc) {
1172 default: break;
1173 case ISD::SDIVREM:
1174 case ISD::UDIVREM:
1175 return performDivRemCombine(N, DAG, DCI, Subtarget);
1176 case ISD::SELECT:
1177 return performSELECTCombine(N, DAG, DCI, Subtarget);
1178 case MipsISD::CMovFP_F:
1179 case MipsISD::CMovFP_T:
1180 return performCMovFPCombine(N, DAG, DCI, Subtarget);
1181 case ISD::AND:
1182 return performANDCombine(N, DAG, DCI, Subtarget);
1183 case ISD::OR:
1184 return performORCombine(N, DAG, DCI, Subtarget);
1185 case ISD::ADD:
1186 return performADDCombine(N, DAG, DCI, Subtarget);
1187 case ISD::SHL:
1188 return performSHLCombine(N, DAG, DCI, Subtarget);
1189 case ISD::SUB:
1190 return performSUBCombine(N, DAG, DCI, Subtarget);
1191 case ISD::SIGN_EXTEND:
1192 return performSignExtendCombine(N, DAG, DCI, Subtarget);
1193 }
1194
1195 return SDValue();
1196}
1197
1199 return Subtarget.hasMips32();
1200}
1201
1203 return Subtarget.hasMips32();
1204}
1205
1207 // We can use ANDI+SLTIU as a bit test. Y contains the bit position.
1208 // For MIPSR2 or later, we may be able to use the `ext` instruction or its
1209 // double-word variants.
1210 if (auto *C = dyn_cast<ConstantSDNode>(Y))
1211 return C->getAPIntValue().ule(15);
1212
1213 return false;
1214}
1215
1217 const SDNode *N) const {
1218 assert(((N->getOpcode() == ISD::SHL &&
1219 N->getOperand(0).getOpcode() == ISD::SRL) ||
1220 (N->getOpcode() == ISD::SRL &&
1221 N->getOperand(0).getOpcode() == ISD::SHL)) &&
1222 "Expected shift-shift mask");
1223
1224 if (N->getOperand(0).getValueType().isVector())
1225 return false;
1226 return true;
1227}
1228
1229void
1235
1238{
1239 switch (Op.getOpcode())
1240 {
1241 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
1242 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
1243 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
1244 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
1245 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
1246 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
1247 case ISD::SELECT: return lowerSELECT(Op, DAG);
1248 case ISD::SETCC: return lowerSETCC(Op, DAG);
1249 case ISD::STRICT_FSETCC:
1251 return lowerFSETCC(Op, DAG);
1252 case ISD::VASTART: return lowerVASTART(Op, DAG);
1253 case ISD::VAARG: return lowerVAARG(Op, DAG);
1254 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
1255 case ISD::FABS: return lowerFABS(Op, DAG);
1256 case ISD::FCANONICALIZE:
1257 return lowerFCANONICALIZE(Op, DAG);
1258 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
1259 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
1260 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
1261 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
1262 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
1263 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
1264 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
1265 case ISD::LOAD: return lowerLOAD(Op, DAG);
1266 case ISD::STORE: return lowerSTORE(Op, DAG);
1267 case ISD::EH_DWARF_CFA: return lowerEH_DWARF_CFA(Op, DAG);
1270 return lowerSTRICT_FP_TO_INT(Op, DAG);
1271 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
1273 return lowerREADCYCLECOUNTER(Op, DAG);
1274 case ISD::ConstantFP:
1275 return lowerConstantFP(Op, DAG);
1276 }
1277 return SDValue();
1278}
1279
1280//===----------------------------------------------------------------------===//
1281// Lower helper functions
1282//===----------------------------------------------------------------------===//
1283
1284// addLiveIn - This helper function adds the specified physical register to the
1285// MachineFunction as a live in value. It also creates a corresponding
1286// virtual register for it.
1287static unsigned
1288addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
1289{
1291 MF.getRegInfo().addLiveIn(PReg, VReg);
1292 return VReg;
1293}
1294
1295static MachineBasicBlock *
1297 const TargetInstrInfo &TII, bool Is64Bit,
1298 const DivByZeroTrapKind TrapKind) {
1299 if (NoZeroDivCheck)
1300 return &MBB;
1301
1302 MachineOperand &Divisor = MI.getOperand(2);
1303
1304 if (TrapKind == DivByZeroTrapKind::Break) {
1305 // Build instructions:
1306 // MBB:
1307 // bnez $divisor, $zero, SinkMBB
1308 // MI $dst, $dividend, $divisor (delay slot)
1309 //
1310 // BreakMBB:
1311 // break 7
1312 //
1313 // SinkMBB:
1314 // fallthrough
1315 const DebugLoc &DL = MI.getDebugLoc();
1316 const BasicBlock *BB = MBB.getBasicBlock();
1317
1318 // Place all instructions after MI into SinkMBB.
1319 MachineBasicBlock *SinkMBB = MBB.splitAt(MI, true);
1320
1321 // BreakMBB setup.
1322 MachineFunction *MF = MBB.getParent();
1323 MachineBasicBlock *BreakMBB = MF->CreateMachineBasicBlock(BB);
1324 MF->insert(++MBB.getIterator(), BreakMBB);
1325
1326 // Place the branch at the end of the block. Since MI is defined as having
1327 // no side effects in TableGen, the filler will place it in the branch delay
1328 // slot.
1329 BuildMI(&MBB, DL, TII.get(Mips::BNE))
1330 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
1331 .addReg(Mips::ZERO)
1332 .addMBB(SinkMBB);
1333
1334 // BreakMBB: break 7
1335 BuildMI(BreakMBB, DL, TII.get(Mips::BREAK)).addImm(7).addImm(0);
1336
1337 MBB.addSuccessor(BreakMBB);
1338 BreakMBB->addSuccessor(SinkMBB);
1339
1340 Divisor.setIsKill(false);
1341
1342 return SinkMBB;
1343 }
1344
1345 // Insert instruction "teq $divisor_reg, $zero, 7".
1348 MIB = BuildMI(MBB, std::next(I), MI.getDebugLoc(),
1349 TII.get(TrapKind == DivByZeroTrapKind::TeqMM ? Mips::TEQ_MM
1350 : Mips::TEQ))
1351 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
1352 .addReg(Mips::ZERO)
1353 .addImm(7);
1354
1355 // Use the 32-bit sub-register if this is a 64-bit division.
1356 if (Is64Bit)
1357 MIB->getOperand(0).setSubReg(Mips::sub_32);
1358
1359 // Clear Divisor's kill flag.
1360 Divisor.setIsKill(false);
1361
1362 // We would normally delete the original instruction here but in this case
1363 // we only needed to inject an additional instruction rather than replace it.
1364
1365 return &MBB;
1366}
1367
1370 MachineBasicBlock *BB) const {
1371 switch (MI.getOpcode()) {
1372 default:
1373 llvm_unreachable("Unexpected instr type to insert");
1374 case Mips::ATOMIC_LOAD_ADD_I8:
1375 return emitAtomicBinaryPartword(MI, BB, 1);
1376 case Mips::ATOMIC_LOAD_ADD_I16:
1377 return emitAtomicBinaryPartword(MI, BB, 2);
1378 case Mips::ATOMIC_LOAD_ADD_I32:
1379 return emitAtomicBinary(MI, BB);
1380 case Mips::ATOMIC_LOAD_ADD_I64:
1381 return emitAtomicBinary(MI, BB);
1382
1383 case Mips::ATOMIC_LOAD_AND_I8:
1384 return emitAtomicBinaryPartword(MI, BB, 1);
1385 case Mips::ATOMIC_LOAD_AND_I16:
1386 return emitAtomicBinaryPartword(MI, BB, 2);
1387 case Mips::ATOMIC_LOAD_AND_I32:
1388 return emitAtomicBinary(MI, BB);
1389 case Mips::ATOMIC_LOAD_AND_I64:
1390 return emitAtomicBinary(MI, BB);
1391
1392 case Mips::ATOMIC_LOAD_OR_I8:
1393 return emitAtomicBinaryPartword(MI, BB, 1);
1394 case Mips::ATOMIC_LOAD_OR_I16:
1395 return emitAtomicBinaryPartword(MI, BB, 2);
1396 case Mips::ATOMIC_LOAD_OR_I32:
1397 return emitAtomicBinary(MI, BB);
1398 case Mips::ATOMIC_LOAD_OR_I64:
1399 return emitAtomicBinary(MI, BB);
1400
1401 case Mips::ATOMIC_LOAD_XOR_I8:
1402 return emitAtomicBinaryPartword(MI, BB, 1);
1403 case Mips::ATOMIC_LOAD_XOR_I16:
1404 return emitAtomicBinaryPartword(MI, BB, 2);
1405 case Mips::ATOMIC_LOAD_XOR_I32:
1406 return emitAtomicBinary(MI, BB);
1407 case Mips::ATOMIC_LOAD_XOR_I64:
1408 return emitAtomicBinary(MI, BB);
1409
1410 case Mips::ATOMIC_LOAD_NAND_I8:
1411 return emitAtomicBinaryPartword(MI, BB, 1);
1412 case Mips::ATOMIC_LOAD_NAND_I16:
1413 return emitAtomicBinaryPartword(MI, BB, 2);
1414 case Mips::ATOMIC_LOAD_NAND_I32:
1415 return emitAtomicBinary(MI, BB);
1416 case Mips::ATOMIC_LOAD_NAND_I64:
1417 return emitAtomicBinary(MI, BB);
1418
1419 case Mips::ATOMIC_LOAD_SUB_I8:
1420 return emitAtomicBinaryPartword(MI, BB, 1);
1421 case Mips::ATOMIC_LOAD_SUB_I16:
1422 return emitAtomicBinaryPartword(MI, BB, 2);
1423 case Mips::ATOMIC_LOAD_SUB_I32:
1424 return emitAtomicBinary(MI, BB);
1425 case Mips::ATOMIC_LOAD_SUB_I64:
1426 return emitAtomicBinary(MI, BB);
1427
1428 case Mips::ATOMIC_SWAP_I8:
1429 return emitAtomicBinaryPartword(MI, BB, 1);
1430 case Mips::ATOMIC_SWAP_I16:
1431 return emitAtomicBinaryPartword(MI, BB, 2);
1432 case Mips::ATOMIC_SWAP_I32:
1433 return emitAtomicBinary(MI, BB);
1434 case Mips::ATOMIC_SWAP_I64:
1435 return emitAtomicBinary(MI, BB);
1436
1437 case Mips::ATOMIC_CMP_SWAP_I8:
1438 return emitAtomicCmpSwapPartword(MI, BB, 1);
1439 case Mips::ATOMIC_CMP_SWAP_I16:
1440 return emitAtomicCmpSwapPartword(MI, BB, 2);
1441 case Mips::ATOMIC_CMP_SWAP_I32:
1442 return emitAtomicCmpSwap(MI, BB);
1443 case Mips::ATOMIC_CMP_SWAP_I64:
1444 return emitAtomicCmpSwap(MI, BB);
1445
1446 case Mips::ATOMIC_LOAD_MIN_I8:
1447 return emitAtomicBinaryPartword(MI, BB, 1);
1448 case Mips::ATOMIC_LOAD_MIN_I16:
1449 return emitAtomicBinaryPartword(MI, BB, 2);
1450 case Mips::ATOMIC_LOAD_MIN_I32:
1451 return emitAtomicBinary(MI, BB);
1452 case Mips::ATOMIC_LOAD_MIN_I64:
1453 return emitAtomicBinary(MI, BB);
1454
1455 case Mips::ATOMIC_LOAD_MAX_I8:
1456 return emitAtomicBinaryPartword(MI, BB, 1);
1457 case Mips::ATOMIC_LOAD_MAX_I16:
1458 return emitAtomicBinaryPartword(MI, BB, 2);
1459 case Mips::ATOMIC_LOAD_MAX_I32:
1460 return emitAtomicBinary(MI, BB);
1461 case Mips::ATOMIC_LOAD_MAX_I64:
1462 return emitAtomicBinary(MI, BB);
1463
1464 case Mips::ATOMIC_LOAD_UMIN_I8:
1465 return emitAtomicBinaryPartword(MI, BB, 1);
1466 case Mips::ATOMIC_LOAD_UMIN_I16:
1467 return emitAtomicBinaryPartword(MI, BB, 2);
1468 case Mips::ATOMIC_LOAD_UMIN_I32:
1469 return emitAtomicBinary(MI, BB);
1470 case Mips::ATOMIC_LOAD_UMIN_I64:
1471 return emitAtomicBinary(MI, BB);
1472
1473 case Mips::ATOMIC_LOAD_UMAX_I8:
1474 return emitAtomicBinaryPartword(MI, BB, 1);
1475 case Mips::ATOMIC_LOAD_UMAX_I16:
1476 return emitAtomicBinaryPartword(MI, BB, 2);
1477 case Mips::ATOMIC_LOAD_UMAX_I32:
1478 return emitAtomicBinary(MI, BB);
1479 case Mips::ATOMIC_LOAD_UMAX_I64:
1480 return emitAtomicBinary(MI, BB);
1481
1482 case Mips::PseudoSDIV:
1483 case Mips::PseudoUDIV:
1484 case Mips::DIV:
1485 case Mips::DIVU:
1486 case Mips::MOD:
1487 case Mips::MODU: {
1488 const DivByZeroTrapKind TrapKind = !Subtarget.hasMips2()
1491 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false,
1492 TrapKind);
1493 }
1494 case Mips::SDIV_MM_Pseudo:
1495 case Mips::UDIV_MM_Pseudo:
1496 case Mips::SDIV_MM:
1497 case Mips::UDIV_MM:
1498 case Mips::DIV_MMR6:
1499 case Mips::DIVU_MMR6:
1500 case Mips::MOD_MMR6:
1501 case Mips::MODU_MMR6:
1502 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false,
1504 case Mips::PseudoDSDIV:
1505 case Mips::PseudoDUDIV:
1506 case Mips::DDIV:
1507 case Mips::DDIVU:
1508 case Mips::DMOD:
1509 case Mips::DMODU:
1510 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true,
1512
1513 case Mips::PseudoSELECT_I:
1514 case Mips::PseudoSELECT_I64:
1515 case Mips::PseudoSELECT_S:
1516 case Mips::PseudoSELECT_D32:
1517 case Mips::PseudoSELECT_D64:
1518 return emitPseudoSELECT(MI, BB, false, Mips::BNE);
1519 case Mips::PseudoSELECTFP_F_I:
1520 case Mips::PseudoSELECTFP_F_I64:
1521 case Mips::PseudoSELECTFP_F_S:
1522 case Mips::PseudoSELECTFP_F_D32:
1523 case Mips::PseudoSELECTFP_F_D64:
1524 return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
1525 case Mips::PseudoSELECTFP_T_I:
1526 case Mips::PseudoSELECTFP_T_I64:
1527 case Mips::PseudoSELECTFP_T_S:
1528 case Mips::PseudoSELECTFP_T_D32:
1529 case Mips::PseudoSELECTFP_T_D64:
1530 return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
1531 case Mips::PseudoD_SELECT_I:
1532 case Mips::PseudoD_SELECT_I64:
1533 return emitPseudoD_SELECT(MI, BB);
1534 case Mips::LDR_W:
1535 return emitLDR_W(MI, BB);
1536 case Mips::LDR_D:
1537 return emitLDR_D(MI, BB);
1538 case Mips::STR_W:
1539 return emitSTR_W(MI, BB);
1540 case Mips::STR_D:
1541 return emitSTR_D(MI, BB);
1542 }
1543}
1544
1545// This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1546// Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1548MipsTargetLowering::emitAtomicBinary(MachineInstr &MI,
1549 MachineBasicBlock *BB) const {
1550
1551 MachineFunction *MF = BB->getParent();
1552 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1554 DebugLoc DL = MI.getDebugLoc();
1555
1556 unsigned AtomicOp;
1557 bool NeedsAdditionalReg = false;
1558 switch (MI.getOpcode()) {
1559 case Mips::ATOMIC_LOAD_ADD_I32:
1560 AtomicOp = Mips::ATOMIC_LOAD_ADD_I32_POSTRA;
1561 break;
1562 case Mips::ATOMIC_LOAD_SUB_I32:
1563 AtomicOp = Mips::ATOMIC_LOAD_SUB_I32_POSTRA;
1564 break;
1565 case Mips::ATOMIC_LOAD_AND_I32:
1566 AtomicOp = Mips::ATOMIC_LOAD_AND_I32_POSTRA;
1567 break;
1568 case Mips::ATOMIC_LOAD_OR_I32:
1569 AtomicOp = Mips::ATOMIC_LOAD_OR_I32_POSTRA;
1570 break;
1571 case Mips::ATOMIC_LOAD_XOR_I32:
1572 AtomicOp = Mips::ATOMIC_LOAD_XOR_I32_POSTRA;
1573 break;
1574 case Mips::ATOMIC_LOAD_NAND_I32:
1575 AtomicOp = Mips::ATOMIC_LOAD_NAND_I32_POSTRA;
1576 break;
1577 case Mips::ATOMIC_SWAP_I32:
1578 AtomicOp = Mips::ATOMIC_SWAP_I32_POSTRA;
1579 break;
1580 case Mips::ATOMIC_LOAD_ADD_I64:
1581 AtomicOp = Mips::ATOMIC_LOAD_ADD_I64_POSTRA;
1582 break;
1583 case Mips::ATOMIC_LOAD_SUB_I64:
1584 AtomicOp = Mips::ATOMIC_LOAD_SUB_I64_POSTRA;
1585 break;
1586 case Mips::ATOMIC_LOAD_AND_I64:
1587 AtomicOp = Mips::ATOMIC_LOAD_AND_I64_POSTRA;
1588 break;
1589 case Mips::ATOMIC_LOAD_OR_I64:
1590 AtomicOp = Mips::ATOMIC_LOAD_OR_I64_POSTRA;
1591 break;
1592 case Mips::ATOMIC_LOAD_XOR_I64:
1593 AtomicOp = Mips::ATOMIC_LOAD_XOR_I64_POSTRA;
1594 break;
1595 case Mips::ATOMIC_LOAD_NAND_I64:
1596 AtomicOp = Mips::ATOMIC_LOAD_NAND_I64_POSTRA;
1597 break;
1598 case Mips::ATOMIC_SWAP_I64:
1599 AtomicOp = Mips::ATOMIC_SWAP_I64_POSTRA;
1600 break;
1601 case Mips::ATOMIC_LOAD_MIN_I32:
1602 AtomicOp = Mips::ATOMIC_LOAD_MIN_I32_POSTRA;
1603 NeedsAdditionalReg = true;
1604 break;
1605 case Mips::ATOMIC_LOAD_MAX_I32:
1606 AtomicOp = Mips::ATOMIC_LOAD_MAX_I32_POSTRA;
1607 NeedsAdditionalReg = true;
1608 break;
1609 case Mips::ATOMIC_LOAD_UMIN_I32:
1610 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I32_POSTRA;
1611 NeedsAdditionalReg = true;
1612 break;
1613 case Mips::ATOMIC_LOAD_UMAX_I32:
1614 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I32_POSTRA;
1615 NeedsAdditionalReg = true;
1616 break;
1617 case Mips::ATOMIC_LOAD_MIN_I64:
1618 AtomicOp = Mips::ATOMIC_LOAD_MIN_I64_POSTRA;
1619 NeedsAdditionalReg = true;
1620 break;
1621 case Mips::ATOMIC_LOAD_MAX_I64:
1622 AtomicOp = Mips::ATOMIC_LOAD_MAX_I64_POSTRA;
1623 NeedsAdditionalReg = true;
1624 break;
1625 case Mips::ATOMIC_LOAD_UMIN_I64:
1626 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I64_POSTRA;
1627 NeedsAdditionalReg = true;
1628 break;
1629 case Mips::ATOMIC_LOAD_UMAX_I64:
1630 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I64_POSTRA;
1631 NeedsAdditionalReg = true;
1632 break;
1633 default:
1634 llvm_unreachable("Unknown pseudo atomic for replacement!");
1635 }
1636
1637 Register OldVal = MI.getOperand(0).getReg();
1638 Register Ptr = MI.getOperand(1).getReg();
1639 Register Incr = MI.getOperand(2).getReg();
1640 Register Scratch = RegInfo.createVirtualRegister(RegInfo.getRegClass(OldVal));
1641
1643
1644 // The scratch registers here with the EarlyClobber | Define | Implicit
1645 // flags is used to persuade the register allocator and the machine
1646 // verifier to accept the usage of this register. This has to be a real
1647 // register which has an UNDEF value but is dead after the instruction which
1648 // is unique among the registers chosen for the instruction.
1649
1650 // The EarlyClobber flag has the semantic properties that the operand it is
1651 // attached to is clobbered before the rest of the inputs are read. Hence it
1652 // must be unique among the operands to the instruction.
1653 // The Define flag is needed to coerce the machine verifier that an Undef
1654 // value isn't a problem.
1655 // The Dead flag is needed as the value in scratch isn't used by any other
1656 // instruction. Kill isn't used as Dead is more precise.
1657 // The implicit flag is here due to the interaction between the other flags
1658 // and the machine verifier.
1659
1660 // For correctness purpose, a new pseudo is introduced here. We need this
1661 // new pseudo, so that FastRegisterAllocator does not see an ll/sc sequence
1662 // that is spread over >1 basic blocks. A register allocator which
1663 // introduces (or any codegen infact) a store, can violate the expectations
1664 // of the hardware.
1665 //
1666 // An atomic read-modify-write sequence starts with a linked load
1667 // instruction and ends with a store conditional instruction. The atomic
1668 // read-modify-write sequence fails if any of the following conditions
1669 // occur between the execution of ll and sc:
1670 // * A coherent store is completed by another process or coherent I/O
1671 // module into the block of synchronizable physical memory containing
1672 // the word. The size and alignment of the block is
1673 // implementation-dependent.
1674 // * A coherent store is executed between an LL and SC sequence on the
1675 // same processor to the block of synchornizable physical memory
1676 // containing the word.
1677 //
1678
1679 Register PtrCopy = RegInfo.createVirtualRegister(RegInfo.getRegClass(Ptr));
1680 Register IncrCopy = RegInfo.createVirtualRegister(RegInfo.getRegClass(Incr));
1681
1682 BuildMI(*BB, II, DL, TII->get(Mips::COPY), IncrCopy).addReg(Incr);
1683 BuildMI(*BB, II, DL, TII->get(Mips::COPY), PtrCopy).addReg(Ptr);
1684
1686 BuildMI(*BB, II, DL, TII->get(AtomicOp))
1688 .addReg(PtrCopy)
1689 .addReg(IncrCopy)
1692 if (NeedsAdditionalReg) {
1693 Register Scratch2 =
1694 RegInfo.createVirtualRegister(RegInfo.getRegClass(OldVal));
1697 }
1698
1699 MI.eraseFromParent();
1700
1701 return BB;
1702}
1703
1704MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1705 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1706 unsigned SrcReg) const {
1707 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1708 const DebugLoc &DL = MI.getDebugLoc();
1709
1710 if (Subtarget.hasMips32r2() && Size == 1) {
1711 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1712 return BB;
1713 }
1714
1715 if (Subtarget.hasMips32r2() && Size == 2) {
1716 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1717 return BB;
1718 }
1719
1720 MachineFunction *MF = BB->getParent();
1721 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1722 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1723 Register ScrReg = RegInfo.createVirtualRegister(RC);
1724
1725 assert(Size < 32);
1726 int64_t ShiftImm = 32 - (Size * 8);
1727
1728 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1729 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1730
1731 return BB;
1732}
1733
1734MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1735 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const {
1736 assert((Size == 1 || Size == 2) &&
1737 "Unsupported size for EmitAtomicBinaryPartial.");
1738
1739 MachineFunction *MF = BB->getParent();
1740 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1741 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1742 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1743 const TargetRegisterClass *RCp =
1744 getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1745 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1746 DebugLoc DL = MI.getDebugLoc();
1747
1748 Register Dest = MI.getOperand(0).getReg();
1749 Register Ptr = MI.getOperand(1).getReg();
1750 Register Incr = MI.getOperand(2).getReg();
1751
1752 Register AlignedAddr = RegInfo.createVirtualRegister(RCp);
1753 Register ShiftAmt = RegInfo.createVirtualRegister(RC);
1754 Register Mask = RegInfo.createVirtualRegister(RC);
1755 Register Mask2 = RegInfo.createVirtualRegister(RC);
1756 Register Incr2 = RegInfo.createVirtualRegister(RC);
1757 Register MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1758 Register PtrLSB2 = RegInfo.createVirtualRegister(RC);
1759 Register MaskUpper = RegInfo.createVirtualRegister(RC);
1760 Register Scratch = RegInfo.createVirtualRegister(RC);
1761 Register Scratch2 = RegInfo.createVirtualRegister(RC);
1762 Register Scratch3 = RegInfo.createVirtualRegister(RC);
1763
1764 unsigned AtomicOp = 0;
1765 bool NeedsAdditionalReg = false;
1766 switch (MI.getOpcode()) {
1767 case Mips::ATOMIC_LOAD_NAND_I8:
1768 AtomicOp = Mips::ATOMIC_LOAD_NAND_I8_POSTRA;
1769 break;
1770 case Mips::ATOMIC_LOAD_NAND_I16:
1771 AtomicOp = Mips::ATOMIC_LOAD_NAND_I16_POSTRA;
1772 break;
1773 case Mips::ATOMIC_SWAP_I8:
1774 AtomicOp = Mips::ATOMIC_SWAP_I8_POSTRA;
1775 break;
1776 case Mips::ATOMIC_SWAP_I16:
1777 AtomicOp = Mips::ATOMIC_SWAP_I16_POSTRA;
1778 break;
1779 case Mips::ATOMIC_LOAD_ADD_I8:
1780 AtomicOp = Mips::ATOMIC_LOAD_ADD_I8_POSTRA;
1781 break;
1782 case Mips::ATOMIC_LOAD_ADD_I16:
1783 AtomicOp = Mips::ATOMIC_LOAD_ADD_I16_POSTRA;
1784 break;
1785 case Mips::ATOMIC_LOAD_SUB_I8:
1786 AtomicOp = Mips::ATOMIC_LOAD_SUB_I8_POSTRA;
1787 break;
1788 case Mips::ATOMIC_LOAD_SUB_I16:
1789 AtomicOp = Mips::ATOMIC_LOAD_SUB_I16_POSTRA;
1790 break;
1791 case Mips::ATOMIC_LOAD_AND_I8:
1792 AtomicOp = Mips::ATOMIC_LOAD_AND_I8_POSTRA;
1793 break;
1794 case Mips::ATOMIC_LOAD_AND_I16:
1795 AtomicOp = Mips::ATOMIC_LOAD_AND_I16_POSTRA;
1796 break;
1797 case Mips::ATOMIC_LOAD_OR_I8:
1798 AtomicOp = Mips::ATOMIC_LOAD_OR_I8_POSTRA;
1799 break;
1800 case Mips::ATOMIC_LOAD_OR_I16:
1801 AtomicOp = Mips::ATOMIC_LOAD_OR_I16_POSTRA;
1802 break;
1803 case Mips::ATOMIC_LOAD_XOR_I8:
1804 AtomicOp = Mips::ATOMIC_LOAD_XOR_I8_POSTRA;
1805 break;
1806 case Mips::ATOMIC_LOAD_XOR_I16:
1807 AtomicOp = Mips::ATOMIC_LOAD_XOR_I16_POSTRA;
1808 break;
1809 case Mips::ATOMIC_LOAD_MIN_I8:
1810 AtomicOp = Mips::ATOMIC_LOAD_MIN_I8_POSTRA;
1811 NeedsAdditionalReg = true;
1812 break;
1813 case Mips::ATOMIC_LOAD_MIN_I16:
1814 AtomicOp = Mips::ATOMIC_LOAD_MIN_I16_POSTRA;
1815 NeedsAdditionalReg = true;
1816 break;
1817 case Mips::ATOMIC_LOAD_MAX_I8:
1818 AtomicOp = Mips::ATOMIC_LOAD_MAX_I8_POSTRA;
1819 NeedsAdditionalReg = true;
1820 break;
1821 case Mips::ATOMIC_LOAD_MAX_I16:
1822 AtomicOp = Mips::ATOMIC_LOAD_MAX_I16_POSTRA;
1823 NeedsAdditionalReg = true;
1824 break;
1825 case Mips::ATOMIC_LOAD_UMIN_I8:
1826 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I8_POSTRA;
1827 NeedsAdditionalReg = true;
1828 break;
1829 case Mips::ATOMIC_LOAD_UMIN_I16:
1830 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I16_POSTRA;
1831 NeedsAdditionalReg = true;
1832 break;
1833 case Mips::ATOMIC_LOAD_UMAX_I8:
1834 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I8_POSTRA;
1835 NeedsAdditionalReg = true;
1836 break;
1837 case Mips::ATOMIC_LOAD_UMAX_I16:
1838 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I16_POSTRA;
1839 NeedsAdditionalReg = true;
1840 break;
1841 default:
1842 llvm_unreachable("Unknown subword atomic pseudo for expansion!");
1843 }
1844
1845 // insert new blocks after the current block
1846 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1847 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1849 MF->insert(It, exitMBB);
1850
1851 // Transfer the remainder of BB and its successor edges to exitMBB.
1852 exitMBB->splice(exitMBB->begin(), BB,
1853 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1855
1857
1858 // thisMBB:
1859 // addiu masklsb2,$0,-4 # 0xfffffffc
1860 // and alignedaddr,ptr,masklsb2
1861 // andi ptrlsb2,ptr,3
1862 // sll shiftamt,ptrlsb2,3
1863 // ori maskupper,$0,255 # 0xff
1864 // sll mask,maskupper,shiftamt
1865 // nor mask2,$0,mask
1866 // sll incr2,incr,shiftamt
1867
1868 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1869 BuildMI(BB, DL, TII->get(ABI.GetPtrAddiuOp()), MaskLSB2)
1870 .addReg(ABI.GetNullPtr()).addImm(-4);
1871 BuildMI(BB, DL, TII->get(ABI.GetPtrAndOp()), AlignedAddr)
1872 .addReg(Ptr).addReg(MaskLSB2);
1873 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1874 .addReg(Ptr, {}, ArePtrs64bit ? Mips::sub_32 : 0)
1875 .addImm(3);
1876 if (Subtarget.isLittle()) {
1877 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1878 } else {
1879 Register Off = RegInfo.createVirtualRegister(RC);
1880 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1881 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1882 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1883 }
1884 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1885 .addReg(Mips::ZERO).addImm(MaskImm);
1886 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1887 .addReg(MaskUpper).addReg(ShiftAmt);
1888 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1889 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1890
1891
1892 // The purposes of the flags on the scratch registers is explained in
1893 // emitAtomicBinary. In summary, we need a scratch register which is going to
1894 // be undef, that is unique among registers chosen for the instruction.
1895
1896 MachineInstrBuilder MIB =
1897 BuildMI(BB, DL, TII->get(AtomicOp))
1899 .addReg(AlignedAddr)
1900 .addReg(Incr2)
1901 .addReg(Mask)
1902 .addReg(Mask2)
1903 .addReg(ShiftAmt)
1910 if (NeedsAdditionalReg) {
1911 Register Scratch4 = RegInfo.createVirtualRegister(RC);
1914 }
1915
1916 MI.eraseFromParent(); // The instruction is gone now.
1917
1918 return exitMBB;
1919}
1920
1921// Lower atomic compare and swap to a pseudo instruction, taking care to
1922// define a scratch register for the pseudo instruction's expansion. The
1923// instruction is expanded after the register allocator as to prevent
1924// the insertion of stores between the linked load and the store conditional.
1925
1927MipsTargetLowering::emitAtomicCmpSwap(MachineInstr &MI,
1928 MachineBasicBlock *BB) const {
1929
1930 assert((MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 ||
1931 MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I64) &&
1932 "Unsupported atomic pseudo for EmitAtomicCmpSwap.");
1933
1934 const unsigned Size = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 ? 4 : 8;
1935
1936 MachineFunction *MF = BB->getParent();
1937 MachineRegisterInfo &MRI = MF->getRegInfo();
1939 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1940 DebugLoc DL = MI.getDebugLoc();
1941
1942 unsigned AtomicOp = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32
1943 ? Mips::ATOMIC_CMP_SWAP_I32_POSTRA
1944 : Mips::ATOMIC_CMP_SWAP_I64_POSTRA;
1945 Register Dest = MI.getOperand(0).getReg();
1946 Register Ptr = MI.getOperand(1).getReg();
1947 Register OldVal = MI.getOperand(2).getReg();
1948 Register NewVal = MI.getOperand(3).getReg();
1949
1950 Register Scratch = MRI.createVirtualRegister(RC);
1952
1953 // We need to create copies of the various registers and kill them at the
1954 // atomic pseudo. If the copies are not made, when the atomic is expanded
1955 // after fast register allocation, the spills will end up outside of the
1956 // blocks that their values are defined in, causing livein errors.
1957
1958 Register PtrCopy = MRI.createVirtualRegister(MRI.getRegClass(Ptr));
1959 Register OldValCopy = MRI.createVirtualRegister(MRI.getRegClass(OldVal));
1960 Register NewValCopy = MRI.createVirtualRegister(MRI.getRegClass(NewVal));
1961
1962 BuildMI(*BB, II, DL, TII->get(Mips::COPY), PtrCopy).addReg(Ptr);
1963 BuildMI(*BB, II, DL, TII->get(Mips::COPY), OldValCopy).addReg(OldVal);
1964 BuildMI(*BB, II, DL, TII->get(Mips::COPY), NewValCopy).addReg(NewVal);
1965
1966 // The purposes of the flags on the scratch registers is explained in
1967 // emitAtomicBinary. In summary, we need a scratch register which is going to
1968 // be undef, that is unique among registers chosen for the instruction.
1969
1970 BuildMI(*BB, II, DL, TII->get(AtomicOp))
1972 .addReg(PtrCopy, RegState::Kill)
1973 .addReg(OldValCopy, RegState::Kill)
1974 .addReg(NewValCopy, RegState::Kill)
1977
1978 MI.eraseFromParent(); // The instruction is gone now.
1979
1980 return BB;
1981}
1982
1983MachineBasicBlock *MipsTargetLowering::emitAtomicCmpSwapPartword(
1984 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const {
1985 assert((Size == 1 || Size == 2) &&
1986 "Unsupported size for EmitAtomicCmpSwapPartial.");
1987
1988 MachineFunction *MF = BB->getParent();
1989 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1990 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1991 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1992 const TargetRegisterClass *RCp =
1993 getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1994 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1995 DebugLoc DL = MI.getDebugLoc();
1996
1997 Register Dest = MI.getOperand(0).getReg();
1998 Register Ptr = MI.getOperand(1).getReg();
1999 Register CmpVal = MI.getOperand(2).getReg();
2000 Register NewVal = MI.getOperand(3).getReg();
2001
2002 Register AlignedAddr = RegInfo.createVirtualRegister(RCp);
2003 Register ShiftAmt = RegInfo.createVirtualRegister(RC);
2004 Register Mask = RegInfo.createVirtualRegister(RC);
2005 Register Mask2 = RegInfo.createVirtualRegister(RC);
2006 Register ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
2007 Register ShiftedNewVal = RegInfo.createVirtualRegister(RC);
2008 Register MaskLSB2 = RegInfo.createVirtualRegister(RCp);
2009 Register PtrLSB2 = RegInfo.createVirtualRegister(RC);
2010 Register MaskUpper = RegInfo.createVirtualRegister(RC);
2011 Register MaskedCmpVal = RegInfo.createVirtualRegister(RC);
2012 Register MaskedNewVal = RegInfo.createVirtualRegister(RC);
2013 unsigned AtomicOp = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I8
2014 ? Mips::ATOMIC_CMP_SWAP_I8_POSTRA
2015 : Mips::ATOMIC_CMP_SWAP_I16_POSTRA;
2016
2017 // The scratch registers here with the EarlyClobber | Define | Dead | Implicit
2018 // flags are used to coerce the register allocator and the machine verifier to
2019 // accept the usage of these registers.
2020 // The EarlyClobber flag has the semantic properties that the operand it is
2021 // attached to is clobbered before the rest of the inputs are read. Hence it
2022 // must be unique among the operands to the instruction.
2023 // The Define flag is needed to coerce the machine verifier that an Undef
2024 // value isn't a problem.
2025 // The Dead flag is needed as the value in scratch isn't used by any other
2026 // instruction. Kill isn't used as Dead is more precise.
2027 Register Scratch = RegInfo.createVirtualRegister(RC);
2028 Register Scratch2 = RegInfo.createVirtualRegister(RC);
2029
2030 // insert new blocks after the current block
2031 const BasicBlock *LLVM_BB = BB->getBasicBlock();
2032 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
2034 MF->insert(It, exitMBB);
2035
2036 // Transfer the remainder of BB and its successor edges to exitMBB.
2037 exitMBB->splice(exitMBB->begin(), BB,
2038 std::next(MachineBasicBlock::iterator(MI)), BB->end());
2040
2042
2043 // thisMBB:
2044 // addiu masklsb2,$0,-4 # 0xfffffffc
2045 // and alignedaddr,ptr,masklsb2
2046 // andi ptrlsb2,ptr,3
2047 // xori ptrlsb2,ptrlsb2,3 # Only for BE
2048 // sll shiftamt,ptrlsb2,3
2049 // ori maskupper,$0,255 # 0xff
2050 // sll mask,maskupper,shiftamt
2051 // nor mask2,$0,mask
2052 // andi maskedcmpval,cmpval,255
2053 // sll shiftedcmpval,maskedcmpval,shiftamt
2054 // andi maskednewval,newval,255
2055 // sll shiftednewval,maskednewval,shiftamt
2056 int64_t MaskImm = (Size == 1) ? 255 : 65535;
2057 BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::DADDiu : Mips::ADDiu), MaskLSB2)
2058 .addReg(ABI.GetNullPtr()).addImm(-4);
2059 BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::AND64 : Mips::AND), AlignedAddr)
2060 .addReg(Ptr).addReg(MaskLSB2);
2061 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
2062 .addReg(Ptr, {}, ArePtrs64bit ? Mips::sub_32 : 0)
2063 .addImm(3);
2064 if (Subtarget.isLittle()) {
2065 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
2066 } else {
2067 Register Off = RegInfo.createVirtualRegister(RC);
2068 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
2069 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
2070 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
2071 }
2072 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
2073 .addReg(Mips::ZERO).addImm(MaskImm);
2074 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
2075 .addReg(MaskUpper).addReg(ShiftAmt);
2076 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
2077 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
2078 .addReg(CmpVal).addImm(MaskImm);
2079 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
2080 .addReg(MaskedCmpVal).addReg(ShiftAmt);
2081 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
2082 .addReg(NewVal).addImm(MaskImm);
2083 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
2084 .addReg(MaskedNewVal).addReg(ShiftAmt);
2085
2086 // The purposes of the flags on the scratch registers are explained in
2087 // emitAtomicBinary. In summary, we need a scratch register which is going to
2088 // be undef, that is unique among the register chosen for the instruction.
2089
2090 BuildMI(BB, DL, TII->get(AtomicOp))
2092 .addReg(AlignedAddr)
2093 .addReg(Mask)
2094 .addReg(ShiftedCmpVal)
2095 .addReg(Mask2)
2096 .addReg(ShiftedNewVal)
2097 .addReg(ShiftAmt)
2102
2103 MI.eraseFromParent(); // The instruction is gone now.
2104
2105 return exitMBB;
2106}
2107
2108SDValue MipsTargetLowering::lowerConstantFP(SDValue Op,
2109 SelectionDAG &DAG) const {
2110 EVT VT = Op.getValueType();
2111 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
2112 const APFloat &FPVal = CFP->getValueAPF();
2113
2114 if (FPVal.isZero())
2115 return SDValue();
2116
2117 SDLoc DL(CFP);
2118 APInt INTVal = FPVal.bitcastToAPInt();
2119 switch (VT.getSimpleVT().SimpleTy) {
2120 default:
2121 llvm_unreachable("Unknown floating point type!");
2122 break;
2123 case MVT::f64: {
2124 if (!Subtarget.hasMTHC1() || !Subtarget.hasMips32r2())
2125 return SDValue();
2126 uint64_t Bits = INTVal.getZExtValue();
2127 uint32_t Lo = Bits & 0xFFFFFFFF;
2128 if (Lo != 0 || Bits == 0)
2129 return SDValue();
2130
2131 // TODO: DAG.getConstant(0) should be optimized to avoid generate an extra
2132 // instr `addiu $x, $zero, 0`.
2133 SDValue Low =
2134 DAG.getCopyFromReg(DAG.getEntryNode(), DL, Mips::ZERO, MVT::i32);
2135 SDValue Hi = DAG.getConstant(INTVal.extractBits(32, 32), DL, MVT::i32);
2136 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, Low, Hi);
2137 }
2138 }
2139
2140 return SDValue();
2141}
2142
2143SDValue MipsTargetLowering::lowerREADCYCLECOUNTER(SDValue Op,
2144 SelectionDAG &DAG) const {
2146 SDLoc DL(Op);
2148 unsigned RdhwrOpc, DestReg;
2149 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2150
2151 if (PtrVT == MVT::i64) {
2152 RdhwrOpc = Mips::RDHWR64;
2153 DestReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
2154 SDNode *Rdhwr = DAG.getMachineNode(RdhwrOpc, DL, MVT::i64, MVT::Glue,
2155 DAG.getRegister(Mips::HWR2, MVT::i32),
2156 DAG.getTargetConstant(0, DL, MVT::i32));
2157 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, DestReg,
2158 SDValue(Rdhwr, 0), SDValue(Rdhwr, 1));
2159 SDValue ResNode =
2160 DAG.getCopyFromReg(Chain, DL, DestReg, MVT::i64, Chain.getValue(1));
2161 Results.push_back(ResNode);
2162 Results.push_back(ResNode.getValue(1));
2163 } else {
2164 RdhwrOpc = Mips::RDHWR;
2165 DestReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2166 SDNode *Rdhwr = DAG.getMachineNode(RdhwrOpc, DL, MVT::i32, MVT::Glue,
2167 DAG.getRegister(Mips::HWR2, MVT::i32),
2168 DAG.getTargetConstant(0, DL, MVT::i32));
2169 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, DestReg,
2170 SDValue(Rdhwr, 0), SDValue(Rdhwr, 1));
2171 SDValue ResNode =
2172 DAG.getCopyFromReg(Chain, DL, DestReg, MVT::i32, Chain.getValue(1));
2173 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResNode,
2174 DAG.getConstant(0, DL, MVT::i32)));
2175 Results.push_back(ResNode.getValue(1));
2176 }
2177
2178 return DAG.getMergeValues(Results, DL);
2179}
2180
2181SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
2182 // The first operand is the chain, the second is the condition, the third is
2183 // the block to branch to if the condition is true.
2184 SDValue Chain = Op.getOperand(0);
2185 SDValue Dest = Op.getOperand(2);
2186 SDLoc DL(Op);
2187
2188 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
2189 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
2190
2191 // Return if flag is not set by a floating point comparison.
2192 if (CondRes.getOpcode() != MipsISD::FPCmp)
2193 return Op;
2194
2195 SDValue CCNode = CondRes.getOperand(2);
2198 SDValue BrCode = DAG.getConstant(Opc, DL, MVT::i32);
2199 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
2200 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
2201 FCC0, Dest, CondRes);
2202}
2203
2204SDValue MipsTargetLowering::
2205lowerSELECT(SDValue Op, SelectionDAG &DAG) const
2206{
2207 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
2208 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
2209
2210 // Return if flag is not set by a floating point comparison.
2211 if (Cond.getOpcode() != MipsISD::FPCmp)
2212 return Op;
2213
2214 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
2215 SDLoc(Op));
2216}
2217
2218SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2219 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
2220 SDValue Cond = createFPCmp(DAG, Op);
2221
2222 assert(Cond.getOpcode() == MipsISD::FPCmp &&
2223 "Floating point operand expected.");
2224
2225 SDLoc DL(Op);
2226 SDValue True = DAG.getConstant(1, DL, MVT::i32);
2227 SDValue False = DAG.getConstant(0, DL, MVT::i32);
2228
2229 return createCMovFP(DAG, Cond, True, False, DL);
2230}
2231
2232SDValue MipsTargetLowering::lowerFSETCC(SDValue Op, SelectionDAG &DAG) const {
2233 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
2234
2235 SDLoc DL(Op);
2236 SDValue Chain = Op.getOperand(0);
2237 SDValue LHS = Op.getOperand(1);
2238 SDValue RHS = Op.getOperand(2);
2239 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
2240
2241 SDValue Cond = DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
2242 DAG.getConstant(condCodeToFCC(CC), DL, MVT::i32));
2243 SDValue True = DAG.getConstant(1, DL, MVT::i32);
2244 SDValue False = DAG.getConstant(0, DL, MVT::i32);
2245 SDValue CMovFP = createCMovFP(DAG, Cond, True, False, DL);
2246
2247 return DAG.getMergeValues({CMovFP, Chain}, DL);
2248}
2249
2250SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
2251 SelectionDAG &DAG) const {
2252 EVT Ty = Op.getValueType();
2253 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
2254 const GlobalValue *GV = N->getGlobal();
2255
2256 if (GV->hasDLLImportStorageClass()) {
2257 assert(Subtarget.isTargetWindows() &&
2258 "Windows is the only supported COFF target");
2259 return getDllimportVariable(
2260 N, SDLoc(N), Ty, DAG, DAG.getEntryNode(),
2262 }
2263
2264 if (!isPositionIndependent()) {
2265 const MipsTargetObjectFile *TLOF =
2266 static_cast<const MipsTargetObjectFile *>(
2268 const GlobalObject *GO = GV->getAliaseeObject();
2269 if (Subtarget.useSmallSection() && GO && TLOF->IsGlobalInSmallSection(GO))
2270 // %gp_rel relocation
2271 return getAddrGPRel(N, SDLoc(N), Ty, DAG, ABI.IsN64());
2272
2273 // %hi/%lo relocation
2274 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2275 // %highest/%higher/%hi/%lo relocation
2276 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2277 }
2278
2279 // Every other architecture would use shouldAssumeDSOLocal in here, but
2280 // mips is special.
2281 // * In PIC code mips requires got loads even for local statics!
2282 // * To save on got entries, for local statics the got entry contains the
2283 // page and an additional add instruction takes care of the low bits.
2284 // * It is legal to access a hidden symbol with a non hidden undefined,
2285 // so one cannot guarantee that all access to a hidden symbol will know
2286 // it is hidden.
2287 // * Mips linkers don't support creating a page and a full got entry for
2288 // the same symbol.
2289 // * Given all that, we have to use a full got entry for hidden symbols :-(
2290 if (GV->hasLocalLinkage())
2291 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2292
2293 if (Subtarget.useXGOT())
2294 return getAddrGlobalLargeGOT(
2295 N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16, MipsII::MO_GOT_LO16,
2296 DAG.getEntryNode(),
2298
2299 return getAddrGlobal(
2300 N, SDLoc(N), Ty, DAG,
2301 (ABI.IsN32() || ABI.IsN64()) ? MipsII::MO_GOT_DISP : MipsII::MO_GOT,
2303}
2304
2305SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
2306 SelectionDAG &DAG) const {
2307 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
2308 EVT Ty = Op.getValueType();
2309
2310 if (!isPositionIndependent())
2311 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2312 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2313
2314 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2315}
2316
2317SDValue MipsTargetLowering::
2318lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
2319{
2320 // If the relocation model is PIC, use the General Dynamic TLS Model or
2321 // Local Dynamic TLS model, otherwise use the Initial Exec or
2322 // Local Exec TLS Model.
2323
2324 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2325 if (DAG.getTarget().useEmulatedTLS())
2326 return LowerToTLSEmulatedModel(GA, DAG);
2327
2328 SDLoc DL(GA);
2329 const GlobalValue *GV = GA->getGlobal();
2330 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2331
2333
2334 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
2335 // General Dynamic and Local Dynamic TLS Model.
2336 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
2337 : MipsII::MO_TLSGD;
2338
2339 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
2340 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
2341 getGlobalReg(DAG, PtrVT), TGA);
2342 unsigned PtrSize = PtrVT.getSizeInBits();
2343 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
2344
2345 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
2346
2348 Args.emplace_back(Argument, PtrTy);
2349
2350 TargetLowering::CallLoweringInfo CLI(DAG);
2351 CLI.setDebugLoc(DL)
2352 .setChain(DAG.getEntryNode())
2353 .setLibCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args));
2354 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2355
2356 SDValue Ret = CallResult.first;
2357
2358 if (model != TLSModel::LocalDynamic)
2359 return Ret;
2360
2361 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2363 SDValue Hi = DAG.getNode(MipsISD::TlsHi, DL, PtrVT, TGAHi);
2364 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2366 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2367 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
2368 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
2369 }
2370
2371 SDValue Offset;
2372 if (model == TLSModel::InitialExec) {
2373 // Initial Exec TLS Model
2374 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2376 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
2377 TGA);
2378 Offset =
2379 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), TGA, MachinePointerInfo());
2380 } else {
2381 // Local Exec TLS Model
2382 assert(model == TLSModel::LocalExec);
2383 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2385 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2387 SDValue Hi = DAG.getNode(MipsISD::TlsHi, DL, PtrVT, TGAHi);
2388 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2389 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2390 }
2391
2392 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
2393 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
2394}
2395
2396SDValue MipsTargetLowering::
2397lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
2398{
2399 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
2400 EVT Ty = Op.getValueType();
2401
2402 if (!isPositionIndependent())
2403 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2404 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2405
2406 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2407}
2408
2409SDValue MipsTargetLowering::
2410lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
2411{
2412 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
2413 EVT Ty = Op.getValueType();
2414
2415 if (!isPositionIndependent()) {
2416 const MipsTargetObjectFile *TLOF =
2417 static_cast<const MipsTargetObjectFile *>(
2419
2420 if (TLOF->IsConstantInSmallSection(DAG.getDataLayout(), N->getConstVal(),
2422 // %gp_rel relocation
2423 return getAddrGPRel(N, SDLoc(N), Ty, DAG, ABI.IsN64());
2424
2425 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2426 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2427 }
2428
2429 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2430}
2431
2432SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2434 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2435
2436 SDLoc DL(Op);
2437 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2439
2440 // vastart just stores the address of the VarArgsFrameIndex slot into the
2441 // memory location argument.
2442 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2443 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
2444 MachinePointerInfo(SV));
2445}
2446
2447SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2448 SDNode *Node = Op.getNode();
2449 EVT VT = Node->getValueType(0);
2450 SDValue Chain = Node->getOperand(0);
2451 SDValue VAListPtr = Node->getOperand(1);
2452 const Align Align =
2453 llvm::MaybeAlign(Node->getConstantOperandVal(3)).valueOrOne();
2454 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2455 SDLoc DL(Node);
2456 unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
2457
2458 SDValue VAListLoad = DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL, Chain,
2459 VAListPtr, MachinePointerInfo(SV));
2460 SDValue VAList = VAListLoad;
2461
2462 // Re-align the pointer if necessary.
2463 // It should only ever be necessary for 64-bit types on O32 since the minimum
2464 // argument alignment is the same as the maximum type alignment for N32/N64.
2465 //
2466 // FIXME: We currently align too often. The code generator doesn't notice
2467 // when the pointer is still aligned from the last va_arg (or pair of
2468 // va_args for the i64 on O32 case).
2469 if (Align > getMinStackArgumentAlignment()) {
2470 VAList = DAG.getNode(
2471 ISD::ADD, DL, VAList.getValueType(), VAList,
2472 DAG.getConstant(Align.value() - 1, DL, VAList.getValueType()));
2473
2474 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
2475 DAG.getSignedConstant(-(int64_t)Align.value(), DL,
2476 VAList.getValueType()));
2477 }
2478
2479 // Increment the pointer, VAList, to the next vaarg.
2480 auto &TD = DAG.getDataLayout();
2481 unsigned ArgSizeInBytes =
2483 SDValue Tmp3 =
2484 DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
2485 DAG.getConstant(alignTo(ArgSizeInBytes, ArgSlotSizeInBytes),
2486 DL, VAList.getValueType()));
2487 // Store the incremented VAList to the legalized pointer
2488 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
2489 MachinePointerInfo(SV));
2490
2491 // In big-endian mode we must adjust the pointer when the load size is smaller
2492 // than the argument slot size. We must also reduce the known alignment to
2493 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
2494 // the correct half of the slot, and reduce the alignment from 8 (slot
2495 // alignment) down to 4 (type alignment).
2496 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
2497 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
2498 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
2499 DAG.getIntPtrConstant(Adjustment, DL));
2500 }
2501 // Load the actual argument out of the pointer VAList
2502 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo());
2503}
2504
2506 bool HasExtractInsert) {
2507 EVT TyX = Op.getOperand(0).getValueType();
2508 EVT TyY = Op.getOperand(1).getValueType();
2509 SDLoc DL(Op);
2510 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2511 SDValue Const31 = DAG.getConstant(31, DL, MVT::i32);
2512 SDValue Res;
2513
2514 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2515 // to i32.
2516 SDValue X = (TyX == MVT::f32) ?
2517 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2518 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2519 Const1);
2520 SDValue Y = (TyY == MVT::f32) ?
2521 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
2522 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
2523 Const1);
2524
2525 if (HasExtractInsert) {
2526 // ext E, Y, 31, 1 ; extract bit31 of Y
2527 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
2528 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2529 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2530 } else {
2531 // sll SllX, X, 1
2532 // srl SrlX, SllX, 1
2533 // srl SrlY, Y, 31
2534 // sll SllY, SrlX, 31
2535 // or Or, SrlX, SllY
2536 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2537 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2538 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2539 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2540 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2541 }
2542
2543 if (TyX == MVT::f32)
2544 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2545
2546 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2547 Op.getOperand(0),
2548 DAG.getConstant(0, DL, MVT::i32));
2549 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2550}
2551
2553 bool HasExtractInsert) {
2554 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2555 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2556 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2557 SDLoc DL(Op);
2558 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2559
2560 // Bitcast to integer nodes.
2561 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2562 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2563
2564 if (HasExtractInsert) {
2565 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
2566 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
2567 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2568 DAG.getConstant(WidthY - 1, DL, MVT::i32), Const1);
2569
2570 if (WidthX > WidthY)
2571 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2572 else if (WidthY > WidthX)
2573 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2574
2575 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2576 DAG.getConstant(WidthX - 1, DL, MVT::i32), Const1,
2577 X);
2578 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2579 }
2580
2581 // (d)sll SllX, X, 1
2582 // (d)srl SrlX, SllX, 1
2583 // (d)srl SrlY, Y, width(Y)-1
2584 // (d)sll SllY, SrlX, width(Y)-1
2585 // or Or, SrlX, SllY
2586 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2587 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2588 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2589 DAG.getConstant(WidthY - 1, DL, MVT::i32));
2590
2591 if (WidthX > WidthY)
2592 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2593 else if (WidthY > WidthX)
2594 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2595
2596 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2597 DAG.getConstant(WidthX - 1, DL, MVT::i32));
2598 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2599 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2600}
2601
2602SDValue
2603MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2604 if (Subtarget.isGP64bit())
2605 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
2606
2607 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
2608}
2609
2610SDValue MipsTargetLowering::lowerFABS32(SDValue Op, SelectionDAG &DAG,
2611 bool HasExtractInsert) const {
2612 SDLoc DL(Op);
2613 SDValue Res, Const1 = DAG.getConstant(1, DL, MVT::i32);
2614
2615 if (Op->getFlags().hasNoNaNs() || Subtarget.inAbs2008Mode())
2616 return DAG.getNode(MipsISD::FAbs, DL, Op.getValueType(), Op.getOperand(0));
2617
2618 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2619 // to i32.
2620 SDValue X = (Op.getValueType() == MVT::f32)
2621 ? DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0))
2622 : DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2623 Op.getOperand(0), Const1);
2624
2625 // Clear MSB.
2626 if (HasExtractInsert)
2627 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
2628 DAG.getRegister(Mips::ZERO, MVT::i32),
2629 DAG.getConstant(31, DL, MVT::i32), Const1, X);
2630 else {
2631 // TODO: Provide DAG patterns which transform (and x, cst)
2632 // back to a (shl (srl x (clz cst)) (clz cst)) sequence.
2633 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2634 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2635 }
2636
2637 if (Op.getValueType() == MVT::f32)
2638 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
2639
2640 // FIXME: For mips32r2, the sequence of (BuildPairF64 (ins (ExtractElementF64
2641 // Op 1), $zero, 31 1) (ExtractElementF64 Op 0)) and the Op has one use, we
2642 // should be able to drop the usage of mfc1/mtc1 and rewrite the register in
2643 // place.
2644 SDValue LowX =
2645 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2646 DAG.getConstant(0, DL, MVT::i32));
2647 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2648}
2649
2650SDValue MipsTargetLowering::lowerFABS64(SDValue Op, SelectionDAG &DAG,
2651 bool HasExtractInsert) const {
2652 SDLoc DL(Op);
2653 SDValue Res, Const1 = DAG.getConstant(1, DL, MVT::i32);
2654
2655 if (Op->getFlags().hasNoNaNs() || Subtarget.inAbs2008Mode())
2656 return DAG.getNode(MipsISD::FAbs, DL, Op.getValueType(), Op.getOperand(0));
2657
2658 // Bitcast to integer node.
2659 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
2660
2661 // Clear MSB.
2662 if (HasExtractInsert)
2663 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
2664 DAG.getRegister(Mips::ZERO_64, MVT::i64),
2665 DAG.getConstant(63, DL, MVT::i32), Const1, X);
2666 else {
2667 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
2668 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
2669 }
2670
2671 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
2672}
2673
2674SDValue MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
2675 if ((ABI.IsN32() || ABI.IsN64()) && (Op.getValueType() == MVT::f64))
2676 return lowerFABS64(Op, DAG, Subtarget.hasExtractInsert());
2677
2678 return lowerFABS32(Op, DAG, Subtarget.hasExtractInsert());
2679}
2680
2681SDValue MipsTargetLowering::lowerFCANONICALIZE(SDValue Op,
2682 SelectionDAG &DAG) const {
2683 SDLoc DL(Op);
2684 EVT VT = Op.getValueType();
2685 SDValue Operand = Op.getOperand(0);
2686 SDNodeFlags Flags = Op->getFlags();
2687
2688 if (Flags.hasNoNaNs() || DAG.isKnownNeverNaN(Operand))
2689 return Operand;
2690
2691 SDValue Quiet = DAG.getNode(ISD::FADD, DL, VT, Operand, Operand);
2692 return DAG.getSelectCC(DL, Operand, Operand, Quiet, Operand, ISD::SETUO);
2693}
2694
2695SDValue MipsTargetLowering::
2696lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2697 // check the depth
2698 if (Op.getConstantOperandVal(0) != 0) {
2699 DAG.getContext()->emitError(
2700 "return address can be determined only for current frame");
2701 return SDValue();
2702 }
2703
2704 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2705 MFI.setFrameAddressIsTaken(true);
2706 EVT VT = Op.getValueType();
2707 SDLoc DL(Op);
2708 SDValue FrameAddr = DAG.getCopyFromReg(
2709 DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
2710 return FrameAddr;
2711}
2712
2713SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2714 SelectionDAG &DAG) const {
2715 // check the depth
2716 if (Op.getConstantOperandVal(0) != 0) {
2717 DAG.getContext()->emitError(
2718 "return address can be determined only for current frame");
2719 return SDValue();
2720 }
2721
2723 MachineFrameInfo &MFI = MF.getFrameInfo();
2724 MVT VT = Op.getSimpleValueType();
2725 unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
2726 MFI.setReturnAddressIsTaken(true);
2727
2728 // Return RA, which contains the return address. Mark it an implicit live-in.
2730 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2731}
2732
2733// An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2734// generated from __builtin_eh_return (offset, handler)
2735// The effect of this is to adjust the stack pointer by "offset"
2736// and then branch to "handler".
2737SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2738 const {
2740 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2741
2742 MipsFI->setCallsEhReturn();
2743 SDValue Chain = Op.getOperand(0);
2744 SDValue Offset = Op.getOperand(1);
2745 SDValue Handler = Op.getOperand(2);
2746 SDLoc DL(Op);
2747 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2748
2749 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2750 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2751 unsigned OffsetReg = ABI.getReturnRegPtr(1);
2752 unsigned AddrReg = ABI.getReturnRegPtr(0);
2753 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2754 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2755 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2756 DAG.getRegister(OffsetReg, Ty),
2757 DAG.getRegister(AddrReg, getPointerTy(MF.getDataLayout())),
2758 Chain.getValue(1));
2759}
2760
2761SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2762 SelectionDAG &DAG) const {
2763 // FIXME: Need pseudo-fence for 'singlethread' fences
2764 // FIXME: Set SType for weaker fences where supported/appropriate.
2765 unsigned SType = 0;
2766 SDLoc DL(Op);
2767 SyncScope::ID FenceSSID =
2768 static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
2769
2770 if (Subtarget.hasMips2() && FenceSSID == SyncScope::System)
2771 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2772 DAG.getTargetConstant(SType, DL, MVT::i32));
2773
2774 // singlethread fences only synchronize with signal handlers on the same
2775 // thread and thus only need to preserve instruction order, not actually
2776 // enforce memory ordering.
2777 if ((Subtarget.hasMips1() && !Subtarget.hasMips2()) ||
2778 FenceSSID == SyncScope::SingleThread) {
2779 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
2780 return DAG.getNode(ISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
2781 }
2782
2783 return Op;
2784}
2785
2786SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2787 SelectionDAG &DAG) const {
2788 SDLoc DL(Op);
2789 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2790
2791 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2792 SDValue Shamt = Op.getOperand(2);
2793 // if shamt < (VT.bits):
2794 // lo = (shl lo, shamt)
2795 // hi = (or (shl hi, shamt) (srl (srl lo, 1), (xor shamt, (VT.bits-1))))
2796 // else:
2797 // lo = 0
2798 // hi = (shl lo, shamt[4:0])
2799 SDValue Not =
2800 DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2801 DAG.getConstant(VT.getSizeInBits() - 1, DL, MVT::i32));
2802 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2803 DAG.getConstant(1, DL, VT));
2804 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2805 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2806 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2807 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2808 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2809 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2810 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2811 DAG.getConstant(0, DL, VT), ShiftLeftLo);
2812 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2813
2814 SDValue Ops[2] = {Lo, Hi};
2815 return DAG.getMergeValues(Ops, DL);
2816}
2817
2818SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2819 bool IsSRA) const {
2820 SDLoc DL(Op);
2821 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2822 SDValue Shamt = Op.getOperand(2);
2823 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2824
2825 // if shamt < (VT.bits):
2826 // lo = (or (shl (shl hi, 1), (xor shamt, (VT.bits-1))) (srl lo, shamt))
2827 // if isSRA:
2828 // hi = (sra hi, shamt)
2829 // else:
2830 // hi = (srl hi, shamt)
2831 // else:
2832 // if isSRA:
2833 // lo = (sra hi, shamt[4:0])
2834 // hi = (sra hi, 31)
2835 // else:
2836 // lo = (srl hi, shamt[4:0])
2837 // hi = 0
2838 SDValue Not =
2839 DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2840 DAG.getConstant(VT.getSizeInBits() - 1, DL, MVT::i32));
2841 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2842 DAG.getConstant(1, DL, VT));
2843 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2844 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2845 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2846 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2847 DL, VT, Hi, Shamt);
2848 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2849 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2850 SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi,
2851 DAG.getConstant(VT.getSizeInBits() - 1, DL, VT));
2852
2853 if (!(Subtarget.hasMips4() || Subtarget.hasMips32())) {
2854 SDVTList VTList = DAG.getVTList(VT, VT);
2855 return DAG.getNode(Subtarget.isGP64bit() ? MipsISD::DOUBLE_SELECT_I64
2857 DL, VTList, Cond, ShiftRightHi,
2858 IsSRA ? Ext : DAG.getConstant(0, DL, VT), Or,
2859 ShiftRightHi);
2860 }
2861
2862 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2863 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2864 IsSRA ? Ext : DAG.getConstant(0, DL, VT), ShiftRightHi);
2865
2866 SDValue Ops[2] = {Lo, Hi};
2867 return DAG.getMergeValues(Ops, DL);
2868}
2869
2871 SDValue Chain, SDValue Src, unsigned Offset) {
2872 SDValue Ptr = LD->getBasePtr();
2873 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2874 EVT BasePtrVT = Ptr.getValueType();
2875 SDLoc DL(LD);
2876 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2877
2878 if (Offset)
2879 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2880 DAG.getConstant(Offset, DL, BasePtrVT));
2881
2882 SDValue Ops[] = { Chain, Ptr, Src };
2883 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2884 LD->getMemOperand());
2885}
2886
2887// Expand an unaligned 32 or 64-bit integer load node.
2890 EVT MemVT = LD->getMemoryVT();
2891
2892 if (Subtarget.systemSupportsUnalignedAccess())
2893 return Op;
2894
2895 // Return if load is aligned or if MemVT is neither i32 nor i64.
2896 if ((LD->getAlign().value() >= (MemVT.getSizeInBits() / 8)) ||
2897 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2898 return SDValue();
2899
2900 bool IsLittle = Subtarget.isLittle();
2901 EVT VT = Op.getValueType();
2902 ISD::LoadExtType ExtType = LD->getExtensionType();
2903 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2904
2905 assert((VT == MVT::i32) || (VT == MVT::i64));
2906
2907 // Expand
2908 // (set dst, (i64 (load baseptr)))
2909 // to
2910 // (set tmp, (ldl (add baseptr, 7), undef))
2911 // (set dst, (ldr baseptr, tmp))
2912 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2913 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2914 IsLittle ? 7 : 0);
2915 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2916 IsLittle ? 0 : 7);
2917 }
2918
2919 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2920 IsLittle ? 3 : 0);
2921 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2922 IsLittle ? 0 : 3);
2923
2924 // Expand
2925 // (set dst, (i32 (load baseptr))) or
2926 // (set dst, (i64 (sextload baseptr))) or
2927 // (set dst, (i64 (extload baseptr)))
2928 // to
2929 // (set tmp, (lwl (add baseptr, 3), undef))
2930 // (set dst, (lwr baseptr, tmp))
2931 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2932 (ExtType == ISD::EXTLOAD))
2933 return LWR;
2934
2935 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2936
2937 // Expand
2938 // (set dst, (i64 (zextload baseptr)))
2939 // to
2940 // (set tmp0, (lwl (add baseptr, 3), undef))
2941 // (set tmp1, (lwr baseptr, tmp0))
2942 // (set tmp2, (shl tmp1, 32))
2943 // (set dst, (srl tmp2, 32))
2944 SDLoc DL(LD);
2945 SDValue Const32 = DAG.getConstant(32, DL, MVT::i32);
2946 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2947 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2948 SDValue Ops[] = { SRL, LWR.getValue(1) };
2949 return DAG.getMergeValues(Ops, DL);
2950}
2951
2953 SDValue Chain, unsigned Offset) {
2954 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2955 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2956 SDLoc DL(SD);
2957 SDVTList VTList = DAG.getVTList(MVT::Other);
2958
2959 if (Offset)
2960 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2961 DAG.getConstant(Offset, DL, BasePtrVT));
2962
2963 SDValue Ops[] = { Chain, Value, Ptr };
2964 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2965 SD->getMemOperand());
2966}
2967
2968// Expand an unaligned 32 or 64-bit integer store node.
2970 bool IsLittle) {
2971 SDValue Value = SD->getValue(), Chain = SD->getChain();
2972 EVT VT = Value.getValueType();
2973
2974 // Expand
2975 // (store val, baseptr) or
2976 // (truncstore val, baseptr)
2977 // to
2978 // (swl val, (add baseptr, 3))
2979 // (swr val, baseptr)
2980 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2981 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2982 IsLittle ? 3 : 0);
2983 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2984 }
2985
2986 assert(VT == MVT::i64);
2987
2988 // Expand
2989 // (store val, baseptr)
2990 // to
2991 // (sdl val, (add baseptr, 7))
2992 // (sdr val, baseptr)
2993 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2994 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2995}
2996
2997// Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2999 bool SingleFloat) {
3000 SDValue Val = SD->getValue();
3001
3002 if (Val.getOpcode() != ISD::FP_TO_SINT ||
3003 (Val.getValueSizeInBits() > 32 && SingleFloat))
3004 return SDValue();
3005
3007 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
3008 Val.getOperand(0));
3009 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
3010 SD->getPointerInfo(), SD->getAlign(),
3011 SD->getMemOperand()->getFlags());
3012}
3013
3016 EVT MemVT = SD->getMemoryVT();
3017
3018 // Lower unaligned integer stores.
3019 if (!Subtarget.systemSupportsUnalignedAccess() &&
3020 (SD->getAlign().value() < (MemVT.getSizeInBits() / 8)) &&
3021 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
3022 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
3023
3024 return lowerFP_TO_SINT_STORE(SD, DAG, Subtarget.isSingleFloat());
3025}
3026
3027SDValue MipsTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
3028 SelectionDAG &DAG) const {
3029
3030 // Return a fixed StackObject with offset 0 which points to the old stack
3031 // pointer.
3033 EVT ValTy = Op->getValueType(0);
3034 int FI = MFI.CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
3035 return DAG.getFrameIndex(FI, ValTy);
3036}
3037
3038SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
3039 SelectionDAG &DAG) const {
3040 if (Op.getValueSizeInBits() > 32 && Subtarget.isSingleFloat())
3041 return SDValue();
3042
3043 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
3044 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
3045 Op.getOperand(0));
3046 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
3047}
3048
3049SDValue MipsTargetLowering::lowerSTRICT_FP_TO_INT(SDValue Op,
3050 SelectionDAG &DAG) const {
3051 assert(Op->isStrictFPOpcode());
3052 SDValue SrcVal = Op.getOperand(1);
3053 SDLoc Loc(Op);
3054
3055 SDValue Result =
3058 Loc, Op.getValueType(), SrcVal);
3059
3060 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
3061}
3062
3064 static const MCPhysReg RCRegs[] = {Mips::FCR31};
3065 return RCRegs;
3066}
3067
3068//===----------------------------------------------------------------------===//
3069// Calling Convention Implementation
3070//===----------------------------------------------------------------------===//
3071
3072//===----------------------------------------------------------------------===//
3073// TODO: Implement a generic logic using tblgen that can support this.
3074// Mips O32 ABI rules:
3075// ---
3076// i32 - Passed in A0, A1, A2, A3 and stack
3077// f32 - Only passed in f32 registers if no int reg has been used yet to hold
3078// an argument. Otherwise, passed in A1, A2, A3 and stack.
3079// f64 - Only passed in two aliased f32 registers if no int reg has been used
3080// yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
3081// not used, it must be shadowed. If only A3 is available, shadow it and
3082// go to stack.
3083// vXiX - Received as scalarized i32s, passed in A0 - A3 and the stack.
3084// vXf32 - Passed in either a pair of registers {A0, A1}, {A2, A3} or {A0 - A3}
3085// with the remainder spilled to the stack.
3086// vXf64 - Passed in either {A0, A1, A2, A3} or {A2, A3} and in both cases
3087// spilling the remainder to the stack.
3088//
3089// For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
3090//===----------------------------------------------------------------------===//
3091
3092static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
3093 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
3094 Type *OrigTy, CCState &State,
3095 ArrayRef<MCPhysReg> F64Regs) {
3096 const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
3097 State.getMachineFunction().getSubtarget());
3098
3099 const MipsABIInfo &ABI = Subtarget.getABI();
3100 ArrayRef<MCPhysReg> IntRegs = ABI.getArgRegs(false);
3101
3102 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
3103
3104 const MCPhysReg FloatVectorIntRegs[] = {IntRegs[0], IntRegs[2]};
3105
3106 // Do not process byval args here.
3107 if (ArgFlags.isByVal())
3108 return true;
3109
3110 // Promote i8 and i16
3111 if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
3112 if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
3113 LocVT = MVT::i32;
3114 if (ArgFlags.isSExt())
3115 LocInfo = CCValAssign::SExtUpper;
3116 else if (ArgFlags.isZExt())
3117 LocInfo = CCValAssign::ZExtUpper;
3118 else
3119 LocInfo = CCValAssign::AExtUpper;
3120 }
3121 }
3122
3123 // Promote i8 and i16
3124 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
3125 LocVT = MVT::i32;
3126 if (ArgFlags.isSExt())
3127 LocInfo = CCValAssign::SExt;
3128 else if (ArgFlags.isZExt())
3129 LocInfo = CCValAssign::ZExt;
3130 else
3131 LocInfo = CCValAssign::AExt;
3132 }
3133
3134 unsigned Reg;
3135
3136 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
3137 // is true: function is vararg, argument is 3rd or higher, there is previous
3138 // argument which is not f32 or f64.
3139 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 ||
3140 State.getFirstUnallocated(F32Regs) != ValNo;
3141 Align OrigAlign = ArgFlags.getNonZeroOrigAlign();
3142 bool isI64 = (ValVT == MVT::i32 && OrigAlign == Align(8));
3143 bool isVectorFloat = OrigTy->isVectorTy() && OrigTy->isFPOrFPVectorTy();
3144
3145 // The MIPS vector ABI for floats passes them in a pair of registers
3146 if (ValVT == MVT::i32 && isVectorFloat) {
3147 // This is the start of an vector that was scalarized into an unknown number
3148 // of components. It doesn't matter how many there are. Allocate one of the
3149 // notional 8 byte aligned registers which map onto the argument stack, and
3150 // shadow the register lost to alignment requirements.
3151 if (ArgFlags.isSplit()) {
3152 Reg = State.AllocateReg(FloatVectorIntRegs);
3153 if (Reg == Mips::A2)
3154 State.AllocateReg(Mips::A1);
3155 else if (Reg == 0)
3156 State.AllocateReg(Mips::A3);
3157 } else {
3158 // If we're an intermediate component of the split, we can just attempt to
3159 // allocate a register directly.
3160 Reg = State.AllocateReg(IntRegs);
3161 }
3162 } else if (ValVT == MVT::i32 ||
3163 (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
3164 Reg = State.AllocateReg(IntRegs);
3165 // If this is the first part of an i64 arg,
3166 // the allocated register must be either A0 or A2.
3167 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
3168 Reg = State.AllocateReg(IntRegs);
3169 LocVT = MVT::i32;
3170 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
3171 // Allocate int register and shadow next int register. If first
3172 // available register is Mips::A1 or Mips::A3, shadow it too.
3173 Reg = State.AllocateReg(IntRegs);
3174 if (Reg == Mips::A1 || Reg == Mips::A3)
3175 Reg = State.AllocateReg(IntRegs);
3176
3177 if (Reg) {
3178 LocVT = MVT::i32;
3179
3180 State.addLoc(
3181 CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
3182 MCRegister HiReg = State.AllocateReg(IntRegs);
3183 assert(HiReg);
3184 State.addLoc(
3185 CCValAssign::getCustomReg(ValNo, ValVT, HiReg, LocVT, LocInfo));
3186 return false;
3187 }
3188 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
3189 // we are guaranteed to find an available float register
3190 if (ValVT == MVT::f32) {
3191 Reg = State.AllocateReg(F32Regs);
3192 // Shadow int register
3193 State.AllocateReg(IntRegs);
3194 } else {
3195 Reg = State.AllocateReg(F64Regs);
3196 // Shadow int registers
3197 MCRegister Reg2 = State.AllocateReg(IntRegs);
3198 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
3199 State.AllocateReg(IntRegs);
3200 State.AllocateReg(IntRegs);
3201 }
3202 } else
3203 llvm_unreachable("Cannot handle this ValVT.");
3204
3205 if (!Reg) {
3206 unsigned Offset = State.AllocateStack(ValVT.getStoreSize(), OrigAlign);
3207 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
3208 } else
3209 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
3210
3211 return false;
3212}
3213
3214static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT, MVT LocVT,
3215 CCValAssign::LocInfo LocInfo,
3216 ISD::ArgFlagsTy ArgFlags, Type *OrigTy,
3217 CCState &State) {
3218 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
3219
3220 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, OrigTy, State,
3221 F64Regs);
3222}
3223
3224static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT, MVT LocVT,
3225 CCValAssign::LocInfo LocInfo,
3226 ISD::ArgFlagsTy ArgFlags, Type *OrigTy,
3227 CCState &State) {
3228 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
3229
3230 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, OrigTy, State,
3231 F64Regs);
3232}
3233
3234[[maybe_unused]] static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
3235 CCValAssign::LocInfo LocInfo,
3236 ISD::ArgFlagsTy ArgFlags, Type *OrigTy,
3237 CCState &State);
3238
3239#define GET_CALLING_CONV_IMPL
3240#include "MipsGenCallingConv.inc"
3241
3243 return CC_Mips_FixedArg;
3244 }
3245
3247 return RetCC_Mips;
3248 }
3249//===----------------------------------------------------------------------===//
3250// Call Calling Convention Implementation
3251//===----------------------------------------------------------------------===//
3252
3253SDValue MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
3254 SDValue Chain, SDValue Arg,
3255 const SDLoc &DL, bool IsTailCall,
3256 SelectionDAG &DAG) const {
3257 if (!IsTailCall) {
3258 SDValue PtrOff =
3259 DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr,
3261 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo());
3262 }
3263
3265 int FI = MFI.CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
3266 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3267 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(), MaybeAlign(),
3269}
3270
3273 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3274 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
3275 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
3276 SDValue Chain) const {
3277 // Insert node "GP copy globalreg" before call to function.
3278 //
3279 // R_MIPS_CALL* operators (emitted when non-internal functions are called
3280 // in PIC mode) allow symbols to be resolved via lazy binding.
3281 // The lazy binding stub requires GP to point to the GOT.
3282 // Note that we don't need GP to point to the GOT for indirect calls
3283 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
3284 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
3285 // used for the function (that is, Mips linker doesn't generate lazy binding
3286 // stub for a function whose address is taken in the program).
3287 if (IsPICCall && !InternalLinkage && IsCallReloc) {
3288 unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
3289 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
3290 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
3291 }
3292
3293 // Build a sequence of copy-to-reg nodes chained together with token
3294 // chain and flag operands which copy the outgoing args into registers.
3295 // The InGlue in necessary since all emitted instructions must be
3296 // stuck together.
3297 SDValue InGlue;
3298
3299 for (auto &R : RegsToPass) {
3300 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, R.first, R.second, InGlue);
3301 InGlue = Chain.getValue(1);
3302 }
3303
3304 // Add argument registers to the end of the list so that they are
3305 // known live into the call.
3306 for (auto &R : RegsToPass)
3307 Ops.push_back(CLI.DAG.getRegister(R.first, R.second.getValueType()));
3308
3309 // Add a register mask operand representing the call-preserved registers.
3310 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3311 const uint32_t *Mask =
3312 TRI->getCallPreservedMask(CLI.DAG.getMachineFunction(), CLI.CallConv);
3313 assert(Mask && "Missing call preserved mask for calling convention");
3314 if (Subtarget.inMips16HardFloat()) {
3316 StringRef Sym = G->getGlobal()->getName();
3317 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3318 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
3320 }
3321 }
3322 }
3323 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
3324
3325 if (InGlue.getNode())
3326 Ops.push_back(InGlue);
3327}
3328
3330 SDNode *Node) const {
3331 switch (MI.getOpcode()) {
3332 default:
3333 return;
3334 case Mips::JALR:
3335 case Mips::JALRPseudo:
3336 case Mips::JALR64:
3337 case Mips::JALR64Pseudo:
3338 case Mips::JALR16_MM:
3339 case Mips::JALRC16_MMR6:
3340 case Mips::TAILCALLREG:
3341 case Mips::TAILCALLREG64:
3342 case Mips::TAILCALLR6REG:
3343 case Mips::TAILCALL64R6REG:
3344 case Mips::TAILCALLREG_MM:
3345 case Mips::TAILCALLREG_MMR6: {
3346 if (!EmitJalrReloc ||
3347 Subtarget.inMips16Mode() ||
3349 Node->getNumOperands() < 1 ||
3350 Node->getOperand(0).getNumOperands() < 2) {
3351 return;
3352 }
3353 // We are after the callee address, set by LowerCall().
3354 // If added to MI, asm printer will emit .reloc R_MIPS_JALR for the
3355 // symbol.
3356 const SDValue TargetAddr = Node->getOperand(0).getOperand(1);
3357 StringRef Sym;
3358 if (const GlobalAddressSDNode *G =
3360 // We must not emit the R_MIPS_JALR relocation against data symbols
3361 // since this will cause run-time crashes if the linker replaces the
3362 // call instruction with a relative branch to the data symbol.
3363 if (!isa<Function>(G->getGlobal())) {
3364 LLVM_DEBUG(dbgs() << "Not adding R_MIPS_JALR against data symbol "
3365 << G->getGlobal()->getName() << "\n");
3366 return;
3367 }
3368 Sym = G->getGlobal()->getName();
3369 }
3370 else if (const ExternalSymbolSDNode *ES =
3372 Sym = ES->getSymbol();
3373 }
3374
3375 if (Sym.empty())
3376 return;
3377
3378 MachineFunction *MF = MI.getParent()->getParent();
3379 MCSymbol *S = MF->getContext().getOrCreateSymbol(Sym);
3380 LLVM_DEBUG(dbgs() << "Adding R_MIPS_JALR against " << Sym << "\n");
3382 }
3383 }
3384}
3385
3386/// LowerCall - functions arguments are copied from virtual regs to
3387/// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
3388SDValue
3389MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3390 SmallVectorImpl<SDValue> &InVals) const {
3391 SelectionDAG &DAG = CLI.DAG;
3392 SDLoc DL = CLI.DL;
3394 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3396 SDValue Chain = CLI.Chain;
3397 SDValue Callee = CLI.Callee;
3398 bool &IsTailCall = CLI.IsTailCall;
3399 CallingConv::ID CallConv = CLI.CallConv;
3400 bool IsVarArg = CLI.IsVarArg;
3401 const CallBase *CB = CLI.CB;
3402
3404 MachineFrameInfo &MFI = MF.getFrameInfo();
3406 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
3407 bool IsPIC = isPositionIndependent();
3408
3409 // Analyze operands of the call, assigning locations to each operand.
3411 MipsCCState CCInfo(
3412 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
3414
3415 const ExternalSymbolSDNode *ES =
3417
3418 // There is one case where CALLSEQ_START..CALLSEQ_END can be nested, which
3419 // is during the lowering of a call with a byval argument which produces
3420 // a call to memcpy. For the O32 case, this causes the caller to allocate
3421 // stack space for the reserved argument area for the callee, then recursively
3422 // again for the memcpy call. In the NEWABI case, this doesn't occur as those
3423 // ABIs mandate that the callee allocates the reserved argument area. We do
3424 // still produce nested CALLSEQ_START..CALLSEQ_END with zero space though.
3425 //
3426 // If the callee has a byval argument and memcpy is used, we are mandated
3427 // to already have produced a reserved argument area for the callee for O32.
3428 // Therefore, the reserved argument area can be reused for both calls.
3429 //
3430 // Other cases of calling memcpy cannot have a chain with a CALLSEQ_START
3431 // present, as we have yet to hook that node onto the chain.
3432 //
3433 // Hence, the CALLSEQ_START and CALLSEQ_END nodes can be eliminated in this
3434 // case. GCC does a similar trick, in that wherever possible, it calculates
3435 // the maximum out going argument area (including the reserved area), and
3436 // preallocates the stack space on entrance to the caller.
3437 //
3438 // FIXME: We should do the same for efficiency and space.
3439
3440 // Note: The check on the calling convention below must match
3441 // MipsABIInfo::GetCalleeAllocdArgSizeInBytes().
3442 bool MemcpyInByVal = ES && StringRef(ES->getSymbol()) == "memcpy" &&
3443 CallConv != CallingConv::Fast &&
3444 Chain.getOpcode() == ISD::CALLSEQ_START;
3445
3446 // Allocate the reserved argument area. It seems strange to do this from the
3447 // caller side but removing it breaks the frame size calculation.
3448 unsigned ReservedArgArea =
3449 MemcpyInByVal ? 0 : ABI.GetCalleeAllocdArgSizeInBytes(CallConv);
3450 CCInfo.AllocateStack(ReservedArgArea, Align(1));
3451
3452 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
3453
3454 // Get a count of how many bytes are to be pushed on the stack.
3455 unsigned StackSize = CCInfo.getStackSize();
3456
3457 // Call site info for function parameters tracking and call base type info.
3459 // Set type id for call site info.
3460 setTypeIdForCallsiteInfo(CB, MF, CSInfo);
3461
3462 // Check if it's really possible to do a tail call.
3463 // For non-musttail calls, restrict to functions that won't require $gp
3464 // restoration. In PIC mode, calling external functions via tail call can
3465 // cause issues with $gp register handling (see D24763).
3466 bool IsMustTail = CLI.CB && CLI.CB->isMustTailCall();
3467 bool CalleeIsLocal = true;
3469 const GlobalValue *GV = G->getGlobal();
3470 bool HasLocalLinkage = GV->hasLocalLinkage() || GV->hasPrivateLinkage();
3471 bool HasHiddenVisibility =
3473 if (GV->isDeclarationForLinker())
3474 CalleeIsLocal = HasLocalLinkage || HasHiddenVisibility;
3475 else
3476 CalleeIsLocal = GV->isDSOLocal();
3477 }
3478
3479 if (IsTailCall) {
3480 if (!UseMipsTailCalls) {
3481 IsTailCall = false;
3482 if (IsMustTail)
3483 report_fatal_error("failed to perform tail call elimination on a call "
3484 "site marked musttail");
3485 } else {
3486 bool Eligible = isEligibleForTailCallOptimization(
3487 CCInfo, StackSize, *MF.getInfo<MipsFunctionInfo>());
3488 if (!Eligible || !CalleeIsLocal) {
3489 IsTailCall = false;
3490 if (IsMustTail)
3492 "failed to perform tail call elimination on a call "
3493 "site marked musttail");
3494 }
3495 }
3496 }
3497
3498 if (IsTailCall)
3499 ++NumTailCalls;
3500
3501 // Chain is the output chain of the last Load/Store or CopyToReg node.
3502 // ByValChain is the output chain of the last Memcpy node created for copying
3503 // byval arguments to the stack.
3504 unsigned StackAlignment = TFL->getStackAlignment();
3505 StackSize = alignTo(StackSize, StackAlignment);
3506
3507 if (!(IsTailCall || MemcpyInByVal))
3508 Chain = DAG.getCALLSEQ_START(Chain, StackSize, 0, DL);
3509
3510 SDValue StackPtr =
3511 DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP,
3513 std::deque<std::pair<unsigned, SDValue>> RegsToPass;
3514 SmallVector<SDValue, 8> MemOpChains;
3515
3516 CCInfo.rewindByValRegsInfo();
3517
3518 // Walk the register/memloc assignments, inserting copies/loads.
3519 for (unsigned i = 0, e = ArgLocs.size(), OutIdx = 0; i != e; ++i, ++OutIdx) {
3520 SDValue Arg = OutVals[OutIdx];
3521 CCValAssign &VA = ArgLocs[i];
3522 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
3523 ISD::ArgFlagsTy Flags = Outs[OutIdx].Flags;
3524 bool UseUpperBits = false;
3525
3526 // ByVal Arg.
3527 if (Flags.isByVal()) {
3528 unsigned FirstByValReg, LastByValReg;
3529 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3530 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3531
3532 assert(Flags.getByValSize() &&
3533 "ByVal args of size 0 should have been ignored by front-end.");
3534 assert(ByValIdx < CCInfo.getInRegsParamsCount());
3535 assert(!IsTailCall &&
3536 "Do not tail-call optimize if there is a byval argument.");
3537 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
3538 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
3539 VA);
3540 CCInfo.nextInRegsParam();
3541 continue;
3542 }
3543
3544 // Promote the value if needed.
3545 switch (VA.getLocInfo()) {
3546 default:
3547 llvm_unreachable("Unknown loc info!");
3548 case CCValAssign::Full:
3549 if (VA.isRegLoc()) {
3550 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
3551 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
3552 (ValVT == MVT::i64 && LocVT == MVT::f64))
3553 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3554 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
3555 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
3556 Arg, DAG.getConstant(0, DL, MVT::i32));
3557 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
3558 Arg, DAG.getConstant(1, DL, MVT::i32));
3559 if (!Subtarget.isLittle())
3560 std::swap(Lo, Hi);
3561
3562 assert(VA.needsCustom());
3563
3564 Register LocRegLo = VA.getLocReg();
3565 Register LocRegHigh = ArgLocs[++i].getLocReg();
3566 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
3567 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
3568 continue;
3569 }
3570 }
3571 break;
3572 case CCValAssign::BCvt:
3573 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3574 break;
3576 UseUpperBits = true;
3577 [[fallthrough]];
3578 case CCValAssign::SExt:
3579 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
3580 break;
3582 UseUpperBits = true;
3583 [[fallthrough]];
3584 case CCValAssign::ZExt:
3585 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
3586 break;
3588 UseUpperBits = true;
3589 [[fallthrough]];
3590 case CCValAssign::AExt:
3591 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
3592 break;
3593 }
3594
3595 if (UseUpperBits) {
3596 unsigned ValSizeInBits = Outs[OutIdx].ArgVT.getSizeInBits();
3597 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3598 Arg = DAG.getNode(
3599 ISD::SHL, DL, VA.getLocVT(), Arg,
3600 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3601 }
3602
3603 // Arguments that can be passed on register must be kept at
3604 // RegsToPass vector
3605 if (VA.isRegLoc()) {
3606 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3607
3608 // If the parameter is passed through reg $D, which splits into
3609 // two physical registers, avoid creating call site info.
3610 if (Mips::AFGR64RegClass.contains(VA.getLocReg()))
3611 continue;
3612
3613 // Collect CSInfo about which register passes which parameter.
3614 const TargetOptions &Options = DAG.getTarget().Options;
3615 if (Options.EmitCallSiteInfo)
3616 CSInfo.ArgRegPairs.emplace_back(VA.getLocReg(), i);
3617
3618 continue;
3619 }
3620
3621 // Register can't get to this point...
3622 assert(VA.isMemLoc());
3623
3624 // emit ISD::STORE whichs stores the
3625 // parameter value to a stack Location
3626 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
3627 Chain, Arg, DL, IsTailCall, DAG));
3628 }
3629
3630 // Transform all store nodes into one single node because all store
3631 // nodes are independent of each other.
3632 if (!MemOpChains.empty())
3633 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3634
3635 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3636 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3637 // node so that legalize doesn't hack it.
3638
3639 EVT Ty = Callee.getValueType();
3640 bool GlobalOrExternal = false, IsCallReloc = false;
3641
3642 // The long-calls feature is ignored in case of PIC.
3643 // While we do not support -mshared / -mno-shared properly,
3644 // ignore long-calls in case of -mabicalls too.
3645 if (!Subtarget.isABICalls() && !IsPIC) {
3646 // If the function should be called using "long call",
3647 // get its address into a register to prevent using
3648 // of the `jal` instruction for the direct call.
3649 if (auto *N = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3650 if (Subtarget.useLongCalls())
3651 Callee = Subtarget.hasSym32()
3652 ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
3653 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
3654 } else if (auto *N = dyn_cast<GlobalAddressSDNode>(Callee)) {
3655 bool UseLongCalls = Subtarget.useLongCalls();
3656 // If the function has long-call/far/near attribute
3657 // it overrides command line switch pased to the backend.
3658 if (auto *F = dyn_cast<Function>(N->getGlobal())) {
3659 if (F->hasFnAttribute("long-call"))
3660 UseLongCalls = true;
3661 else if (F->hasFnAttribute("short-call"))
3662 UseLongCalls = false;
3663 }
3664 if (UseLongCalls)
3665 Callee = Subtarget.hasSym32()
3666 ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
3667 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
3668 }
3669 }
3670
3671 bool InternalLinkage = false;
3672 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3673 if (Subtarget.isTargetCOFF() &&
3674 G->getGlobal()->hasDLLImportStorageClass()) {
3675 assert(Subtarget.isTargetWindows() &&
3676 "Windows is the only supported COFF target");
3677 auto PtrInfo = MachinePointerInfo();
3678 Callee = DAG.getLoad(Ty, DL, Chain,
3679 getDllimportSymbol(G, SDLoc(G), Ty, DAG), PtrInfo);
3680 } else if (IsPIC) {
3681 const GlobalValue *Val = G->getGlobal();
3682 InternalLinkage = Val->hasInternalLinkage();
3683
3684 if (InternalLinkage)
3685 Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
3686 else if (Subtarget.useXGOT()) {
3688 MipsII::MO_CALL_LO16, Chain,
3689 FuncInfo->callPtrInfo(MF, Val));
3690 IsCallReloc = true;
3691 } else {
3692 Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3693 FuncInfo->callPtrInfo(MF, Val));
3694 IsCallReloc = true;
3695 }
3696 } else
3697 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL,
3698 getPointerTy(DAG.getDataLayout()), 0,
3700 GlobalOrExternal = true;
3701 }
3702 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3703 const char *Sym = S->getSymbol();
3704
3705 if (!IsPIC) // static
3708 else if (Subtarget.useXGOT()) {
3710 MipsII::MO_CALL_LO16, Chain,
3711 FuncInfo->callPtrInfo(MF, Sym));
3712 IsCallReloc = true;
3713 } else { // PIC
3714 Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3715 FuncInfo->callPtrInfo(MF, Sym));
3716 IsCallReloc = true;
3717 }
3718
3719 GlobalOrExternal = true;
3720 }
3721
3722 SmallVector<SDValue, 8> Ops(1, Chain);
3723 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3724
3725 getOpndList(Ops, RegsToPass, IsPIC, GlobalOrExternal, InternalLinkage,
3726 IsCallReloc, CLI, Callee, Chain);
3727
3728 if (IsTailCall) {
3730 SDValue Ret = DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
3731 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
3732 return Ret;
3733 }
3734
3735 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
3736 SDValue InGlue = Chain.getValue(1);
3737
3738 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
3739
3740 // Create the CALLSEQ_END node in the case of where it is not a call to
3741 // memcpy.
3742 if (!(MemcpyInByVal)) {
3743 Chain = DAG.getCALLSEQ_END(Chain, StackSize, 0, InGlue, DL);
3744 InGlue = Chain.getValue(1);
3745 }
3746
3747 // Handle result values, copying them out of physregs into vregs that we
3748 // return.
3749 return LowerCallResult(Chain, InGlue, CallConv, IsVarArg, Ins, DL, DAG,
3750 InVals, CLI);
3751}
3752
3753/// LowerCallResult - Lower the result values of a call into the
3754/// appropriate copies out of appropriate physical registers.
3755SDValue MipsTargetLowering::LowerCallResult(
3756 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool IsVarArg,
3757 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3760 // Assign locations to each value returned by this call.
3762 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
3763 *DAG.getContext());
3764
3765 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
3766
3767 // Copy all of the result registers out of their specified physreg.
3768 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3769 CCValAssign &VA = RVLocs[i];
3770 assert(VA.isRegLoc() && "Can only return in registers!");
3771
3772 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
3773 RVLocs[i].getLocVT(), InGlue);
3774 Chain = Val.getValue(1);
3775 InGlue = Val.getValue(2);
3776
3777 if (VA.isUpperBitsInLoc()) {
3778 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
3779 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3780 unsigned Shift =
3782 Val = DAG.getNode(
3783 Shift, DL, VA.getLocVT(), Val,
3784 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3785 }
3786
3787 switch (VA.getLocInfo()) {
3788 default:
3789 llvm_unreachable("Unknown loc info!");
3790 case CCValAssign::Full:
3791 break;
3792 case CCValAssign::BCvt:
3793 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3794 break;
3795 case CCValAssign::AExt:
3797 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3798 break;
3799 case CCValAssign::ZExt:
3801 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
3802 DAG.getValueType(VA.getValVT()));
3803 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3804 break;
3805 case CCValAssign::SExt:
3807 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
3808 DAG.getValueType(VA.getValVT()));
3809 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3810 break;
3811 }
3812
3813 InVals.push_back(Val);
3814 }
3815
3816 return Chain;
3817}
3818
3820 EVT ArgVT, const SDLoc &DL,
3821 SelectionDAG &DAG) {
3822 MVT LocVT = VA.getLocVT();
3823 EVT ValVT = VA.getValVT();
3824
3825 // Shift into the upper bits if necessary.
3826 switch (VA.getLocInfo()) {
3827 default:
3828 break;
3832 unsigned ValSizeInBits = ArgVT.getSizeInBits();
3833 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3834 unsigned Opcode =
3836 Val = DAG.getNode(
3837 Opcode, DL, VA.getLocVT(), Val,
3838 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3839 break;
3840 }
3841 }
3842
3843 // If this is an value smaller than the argument slot size (32-bit for O32,
3844 // 64-bit for N32/N64), it has been promoted in some way to the argument slot
3845 // size. Extract the value and insert any appropriate assertions regarding
3846 // sign/zero extension.
3847 switch (VA.getLocInfo()) {
3848 default:
3849 llvm_unreachable("Unknown loc info!");
3850 case CCValAssign::Full:
3851 break;
3853 case CCValAssign::AExt:
3854 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3855 break;
3857 case CCValAssign::SExt:
3858 Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
3859 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3860 break;
3862 case CCValAssign::ZExt:
3863 Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
3864 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3865 break;
3866 case CCValAssign::BCvt:
3867 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
3868 break;
3869 }
3870
3871 return Val;
3872}
3873
3874//===----------------------------------------------------------------------===//
3875// Formal Arguments Calling Convention Implementation
3876//===----------------------------------------------------------------------===//
3877/// LowerFormalArguments - transform physical registers into virtual registers
3878/// and generate load operations for arguments places on the stack.
3879SDValue MipsTargetLowering::LowerFormalArguments(
3880 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
3881 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3882 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3884 MachineFrameInfo &MFI = MF.getFrameInfo();
3885 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3886
3887 MipsFI->setVarArgsFrameIndex(0);
3888
3889 // Used with vargs to acumulate store chains.
3890 std::vector<SDValue> OutChains;
3891
3892 // Assign locations to all of the incoming arguments.
3894 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3895 *DAG.getContext());
3896 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), Align(1));
3898 Function::const_arg_iterator FuncArg = Func.arg_begin();
3899
3900 if (Func.hasFnAttribute("interrupt") && !Func.arg_empty())
3902 "Functions with the interrupt attribute cannot have arguments!");
3903
3904 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
3905 MipsFI->setFormalArgInfo(CCInfo.getStackSize(),
3906 CCInfo.getInRegsParamsCount() > 0);
3907
3908 unsigned CurArgIdx = 0;
3909 CCInfo.rewindByValRegsInfo();
3910
3911 for (unsigned i = 0, e = ArgLocs.size(), InsIdx = 0; i != e; ++i, ++InsIdx) {
3912 CCValAssign &VA = ArgLocs[i];
3913 if (Ins[InsIdx].isOrigArg()) {
3914 std::advance(FuncArg, Ins[InsIdx].getOrigArgIndex() - CurArgIdx);
3915 CurArgIdx = Ins[InsIdx].getOrigArgIndex();
3916 }
3917 EVT ValVT = VA.getValVT();
3918 ISD::ArgFlagsTy Flags = Ins[InsIdx].Flags;
3919 bool IsRegLoc = VA.isRegLoc();
3920
3921 if (Flags.isByVal()) {
3922 assert(Ins[InsIdx].isOrigArg() && "Byval arguments cannot be implicit");
3923 unsigned FirstByValReg, LastByValReg;
3924 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3925 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3926
3927 assert(Flags.getByValSize() &&
3928 "ByVal args of size 0 should have been ignored by front-end.");
3929 assert(ByValIdx < CCInfo.getInRegsParamsCount());
3930 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
3931 FirstByValReg, LastByValReg, VA, CCInfo);
3932 CCInfo.nextInRegsParam();
3933 continue;
3934 }
3935
3936 // Arguments stored on registers
3937 if (IsRegLoc) {
3938 MVT RegVT = VA.getLocVT();
3939 Register ArgReg = VA.getLocReg();
3940 const TargetRegisterClass *RC = getRegClassFor(RegVT);
3941
3942 // Transform the arguments stored on
3943 // physical registers into virtual ones
3944 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3945 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3946
3947 ArgValue =
3948 UnpackFromArgumentSlot(ArgValue, VA, Ins[InsIdx].ArgVT, DL, DAG);
3949
3950 // Handle floating point arguments passed in integer registers and
3951 // long double arguments passed in floating point registers.
3952 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3953 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
3954 (RegVT == MVT::f64 && ValVT == MVT::i64))
3955 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
3956 else if (ABI.IsO32() && RegVT == MVT::i32 &&
3957 ValVT == MVT::f64) {
3958 assert(VA.needsCustom() && "Expected custom argument for f64 split");
3959 CCValAssign &NextVA = ArgLocs[++i];
3960 unsigned Reg2 =
3961 addLiveIn(DAG.getMachineFunction(), NextVA.getLocReg(), RC);
3962 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
3963 if (!Subtarget.isLittle())
3964 std::swap(ArgValue, ArgValue2);
3965 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
3966 ArgValue, ArgValue2);
3967 }
3968
3969 InVals.push_back(ArgValue);
3970 } else { // VA.isRegLoc()
3971 MVT LocVT = VA.getLocVT();
3972
3973 assert(!VA.needsCustom() && "unexpected custom memory argument");
3974
3975 // Only arguments pased on the stack should make it here.
3976 assert(VA.isMemLoc());
3977
3978 // The stack pointer offset is relative to the caller stack frame.
3979 int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
3980 VA.getLocMemOffset(), true);
3981
3982 // Create load nodes to retrieve arguments from the stack
3983 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3984 SDValue ArgValue = DAG.getLoad(
3985 LocVT, DL, Chain, FIN,
3987 OutChains.push_back(ArgValue.getValue(1));
3988
3989 ArgValue =
3990 UnpackFromArgumentSlot(ArgValue, VA, Ins[InsIdx].ArgVT, DL, DAG);
3991
3992 InVals.push_back(ArgValue);
3993 }
3994 }
3995
3996 for (unsigned i = 0, e = ArgLocs.size(), InsIdx = 0; i != e; ++i, ++InsIdx) {
3997
3998 if (ArgLocs[i].needsCustom()) {
3999 ++i;
4000 continue;
4001 }
4002
4003 // The mips ABIs for returning structs by value requires that we copy
4004 // the sret argument into $v0 for the return. Save the argument into
4005 // a virtual register so that we can access it from the return points.
4006 if (Ins[InsIdx].Flags.isSRet()) {
4007 unsigned Reg = MipsFI->getSRetReturnReg();
4008 if (!Reg) {
4010 getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32));
4011 MipsFI->setSRetReturnReg(Reg);
4012 }
4013 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
4014 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
4015 break;
4016 }
4017 }
4018
4019 if (IsVarArg)
4020 writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
4021
4022 // All stores are grouped in one node to allow the matching between
4023 // the size of Ins and InVals. This only happens when on varg functions
4024 if (!OutChains.empty()) {
4025 OutChains.push_back(Chain);
4026 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
4027 }
4028
4029 return Chain;
4030}
4031
4032//===----------------------------------------------------------------------===//
4033// Return Value Calling Convention Implementation
4034//===----------------------------------------------------------------------===//
4035
4036bool
4037MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4038 MachineFunction &MF, bool IsVarArg,
4040 LLVMContext &Context, const Type *RetTy) const {
4042 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
4043 return CCInfo.CheckReturn(Outs, RetCC_Mips);
4044}
4045
4046bool MipsTargetLowering::shouldSignExtendTypeInLibCall(Type *Ty,
4047 bool IsSigned) const {
4048 if ((ABI.IsN32() || ABI.IsN64()) && Ty->isIntegerTy(32))
4049 return true;
4050
4051 return IsSigned;
4052}
4053
4054SDValue
4055MipsTargetLowering::LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
4056 const SDLoc &DL,
4057 SelectionDAG &DAG) const {
4059 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4060
4061 MipsFI->setISR();
4062
4063 return DAG.getNode(MipsISD::ERet, DL, MVT::Other, RetOps);
4064}
4065
4066SDValue
4067MipsTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
4068 bool IsVarArg,
4070 const SmallVectorImpl<SDValue> &OutVals,
4071 const SDLoc &DL, SelectionDAG &DAG) const {
4072 // CCValAssign - represent the assignment of
4073 // the return value to a location
4076
4077 // CCState - Info about the registers and stack slot.
4078 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
4079
4080 // Analyze return values.
4081 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
4082
4083 SDValue Glue;
4084 SmallVector<SDValue, 4> RetOps(1, Chain);
4085
4086 // Copy the result values into the output registers.
4087 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4088 SDValue Val = OutVals[i];
4089 CCValAssign &VA = RVLocs[i];
4090 assert(VA.isRegLoc() && "Can only return in registers!");
4091 bool UseUpperBits = false;
4092
4093 switch (VA.getLocInfo()) {
4094 default:
4095 llvm_unreachable("Unknown loc info!");
4096 case CCValAssign::Full:
4097 break;
4098 case CCValAssign::BCvt:
4099 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
4100 break;
4102 UseUpperBits = true;
4103 [[fallthrough]];
4104 case CCValAssign::AExt:
4105 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
4106 break;
4108 UseUpperBits = true;
4109 [[fallthrough]];
4110 case CCValAssign::ZExt:
4111 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
4112 break;
4114 UseUpperBits = true;
4115 [[fallthrough]];
4116 case CCValAssign::SExt:
4117 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
4118 break;
4119 }
4120
4121 if (UseUpperBits) {
4122 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
4123 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
4124 Val = DAG.getNode(
4125 ISD::SHL, DL, VA.getLocVT(), Val,
4126 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
4127 }
4128
4129 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
4130
4131 // Guarantee that all emitted copies are stuck together with flags.
4132 Glue = Chain.getValue(1);
4133 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4134 }
4135
4136 // The mips ABIs for returning structs by value requires that we copy
4137 // the sret argument into $v0 for the return. We saved the argument into
4138 // a virtual register in the entry block, so now we copy the value out
4139 // and into $v0.
4140 if (MF.getFunction().hasStructRetAttr()) {
4141 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4142 unsigned Reg = MipsFI->getSRetReturnReg();
4143
4144 if (!Reg)
4145 llvm_unreachable("sret virtual register not created in the entry block");
4146 SDValue Val =
4147 DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
4148 unsigned V0 = ABI.getReturnRegPtr(0);
4149
4150 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Glue);
4151 Glue = Chain.getValue(1);
4152 RetOps.push_back(DAG.getRegister(V0, getPointerTy(DAG.getDataLayout())));
4153 }
4154
4155 RetOps[0] = Chain; // Update chain.
4156
4157 // Add the glue if we have it.
4158 if (Glue.getNode())
4159 RetOps.push_back(Glue);
4160
4161 // ISRs must use "eret".
4162 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt"))
4163 return LowerInterruptReturn(RetOps, DL, DAG);
4164
4165 // Standard return on Mips is a "jr $ra"
4166 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
4167}
4168
4169//===----------------------------------------------------------------------===//
4170// Mips Inline Assembly Support
4171//===----------------------------------------------------------------------===//
4172
4173/// getConstraintType - Given a constraint letter, return the type of
4174/// constraint it is for this target.
4176MipsTargetLowering::getConstraintType(StringRef Constraint) const {
4177 // Mips specific constraints
4178 // GCC config/mips/constraints.md
4179 //
4180 // 'd' : An address register. Equivalent to r
4181 // unless generating MIPS16 code.
4182 // 'y' : Equivalent to r; retained for
4183 // backwards compatibility.
4184 // 'c' : A register suitable for use in an indirect
4185 // jump. This will always be $25 for -mabicalls.
4186 // 'l' : The lo register. 1 word storage.
4187 // 'x' : The hilo register pair. Double word storage.
4188 if (Constraint.size() == 1) {
4189 switch (Constraint[0]) {
4190 default : break;
4191 case 'd':
4192 case 'y':
4193 case 'f':
4194 case 'c':
4195 case 'l':
4196 case 'x':
4197 return C_RegisterClass;
4198 case 'R':
4199 return C_Memory;
4200 }
4201 }
4202
4203 if (Constraint == "ZC")
4204 return C_Memory;
4205
4206 return TargetLowering::getConstraintType(Constraint);
4207}
4208
4209/// Examine constraint type and operand type and determine a weight value.
4210/// This object must already have been set up with the operand type
4211/// and the current alternative constraint selected.
4213MipsTargetLowering::getSingleConstraintMatchWeight(
4214 AsmOperandInfo &info, const char *constraint) const {
4216 Value *CallOperandVal = info.CallOperandVal;
4217 // If we don't have a value, we can't do a match,
4218 // but allow it at the lowest weight.
4219 if (!CallOperandVal)
4220 return CW_Default;
4221 Type *type = CallOperandVal->getType();
4222 // Look at the constraint type.
4223 switch (*constraint) {
4224 default:
4226 break;
4227 case 'd':
4228 case 'y':
4229 if (type->isIntegerTy())
4230 weight = CW_Register;
4231 break;
4232 case 'f': // FPU or MSA register
4233 if (Subtarget.hasMSA() && type->isVectorTy() &&
4234 type->getPrimitiveSizeInBits().getFixedValue() == 128)
4235 weight = CW_Register;
4236 else if (type->isFloatTy())
4237 weight = CW_Register;
4238 break;
4239 case 'c': // $25 for indirect jumps
4240 case 'l': // lo register
4241 case 'x': // hilo register pair
4242 if (type->isIntegerTy())
4243 weight = CW_SpecificReg;
4244 break;
4245 case 'I': // signed 16 bit immediate
4246 case 'J': // integer zero
4247 case 'K': // unsigned 16 bit immediate
4248 case 'L': // signed 32 bit immediate where lower 16 bits are 0
4249 case 'N': // immediate in the range of -65535 to -1 (inclusive)
4250 case 'O': // signed 15 bit immediate (+- 16383)
4251 case 'P': // immediate in the range of 65535 to 1 (inclusive)
4252 if (isa<ConstantInt>(CallOperandVal))
4253 weight = CW_Constant;
4254 break;
4255 case 'R':
4256 weight = CW_Memory;
4257 break;
4258 }
4259 return weight;
4260}
4261
4262/// This is a helper function to parse a physical register string and split it
4263/// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
4264/// that is returned indicates whether parsing was successful. The second flag
4265/// is true if the numeric part exists.
4266static std::pair<bool, bool> parsePhysicalReg(StringRef C, StringRef &Prefix,
4267 unsigned long long &Reg) {
4268 if (C.front() != '{' || C.back() != '}')
4269 return std::make_pair(false, false);
4270
4271 // Search for the first numeric character.
4272 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
4273 I = std::find_if(B, E, isdigit);
4274
4275 Prefix = StringRef(B, I - B);
4276
4277 // The second flag is set to false if no numeric characters were found.
4278 if (I == E)
4279 return std::make_pair(true, false);
4280
4281 // Parse the numeric characters.
4282 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
4283 true);
4284}
4285
4287 ISD::NodeType) const {
4288 bool Cond = !Subtarget.isABI_O32() && VT.getSizeInBits() == 32;
4289 EVT MinVT = getRegisterType(Context, Cond ? MVT::i64 : MVT::i32);
4290 return VT.bitsLT(MinVT) ? MinVT : VT;
4291}
4292
4293std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
4294parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
4295 const TargetRegisterInfo *TRI =
4297 const TargetRegisterClass *RC;
4298 StringRef Prefix;
4299 unsigned long long Reg;
4300
4301 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
4302
4303 if (!R.first)
4304 return std::make_pair(0U, nullptr);
4305
4306 for (unsigned RegClassID : {Mips::HI32RegClassID, Mips::LO32RegClassID}) {
4308 Prefix, *TRI, RegClassID, Mips::RegAliasName)) {
4309 // No numeric characters follow a hi/lo register name.
4310 if (R.second)
4311 return std::make_pair(0U, nullptr);
4312 return std::make_pair(NamedReg.id(), TRI->getRegClass(RegClassID));
4313 }
4314 }
4315
4316 if (Prefix.starts_with("$msa")) {
4317 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
4318
4319 // No numeric characters follow the name.
4320 if (R.second)
4321 return std::make_pair(0U, nullptr);
4322
4323 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
4325 Prefix.drop_front(), *TRI, Mips::MSACtrlRegClassID, Mips::RegAliasName);
4326 if (!Reg)
4327 return std::make_pair(0U, nullptr);
4328
4329 return std::make_pair(Reg, RC);
4330 }
4331
4332 if (!R.second)
4333 return std::make_pair(0U, nullptr);
4334
4335 if (Prefix == "$f") { // Parse $f0-$f31.
4336 // If the targets is single float only, always select 32-bit registers,
4337 // otherwise if the size of FP registers is 64-bit or Reg is an even number,
4338 // select the 64-bit register class. Otherwise, select the 32-bit register
4339 // class.
4340 if (VT == MVT::Other) {
4341 if (Subtarget.isSingleFloat())
4342 VT = MVT::f32;
4343 else
4344 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
4345 }
4346
4347 RC = getRegClassFor(VT);
4348
4349 if (RC == &Mips::AFGR64RegClass) {
4350 assert(Reg % 2 == 0);
4351 Reg >>= 1;
4352 }
4353 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
4354 RC = TRI->getRegClass(Mips::FCCRegClassID);
4355 else if (Prefix == "$w") { // Parse $w0-$w31.
4356 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
4357 } else { // Parse $0-$31.
4358 assert(Prefix == "$");
4359 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
4360 }
4361
4362 assert(Reg < RC->getNumRegs());
4363 return std::make_pair(*(RC->begin() + Reg), RC);
4364}
4365
4366/// Given a register class constraint, like 'r', if this corresponds directly
4367/// to an LLVM register class, return a register of 0 and the register class
4368/// pointer.
4369std::pair<unsigned, const TargetRegisterClass *>
4370MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
4371 StringRef Constraint,
4372 MVT VT) const {
4373 if (Constraint.size() == 1) {
4374 switch (Constraint[0]) {
4375 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
4376 case 'y': // Same as 'r'. Exists for compatibility.
4377 case 'r':
4378 if ((VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8 ||
4379 VT == MVT::i1) ||
4380 (VT == MVT::f32 && Subtarget.useSoftFloat())) {
4381 if (Subtarget.inMips16Mode())
4382 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
4383 return std::make_pair(0U, &Mips::GPR32RegClass);
4384 }
4385 if ((VT == MVT::i64 || (VT == MVT::f64 && Subtarget.useSoftFloat()) ||
4386 (VT == MVT::f64 && Subtarget.isSingleFloat())) &&
4387 !Subtarget.isGP64bit())
4388 return std::make_pair(0U, &Mips::GPR32RegClass);
4389 if ((VT == MVT::i64 || (VT == MVT::f64 && Subtarget.useSoftFloat()) ||
4390 (VT == MVT::f64 && Subtarget.isSingleFloat())) &&
4391 Subtarget.isGP64bit())
4392 return std::make_pair(0U, &Mips::GPR64RegClass);
4393 // This will generate an error message
4394 return std::make_pair(0U, nullptr);
4395 case 'f': // FPU or MSA register
4396 if (VT == MVT::v16i8)
4397 return std::make_pair(0U, &Mips::MSA128BRegClass);
4398 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
4399 return std::make_pair(0U, &Mips::MSA128HRegClass);
4400 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
4401 return std::make_pair(0U, &Mips::MSA128WRegClass);
4402 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
4403 return std::make_pair(0U, &Mips::MSA128DRegClass);
4404 else if (VT == MVT::f32)
4405 return std::make_pair(0U, &Mips::FGR32RegClass);
4406 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
4407 if (Subtarget.isFP64bit())
4408 return std::make_pair(0U, &Mips::FGR64RegClass);
4409 return std::make_pair(0U, &Mips::AFGR64RegClass);
4410 }
4411 break;
4412 case 'c': // register suitable for indirect jump
4413 if (VT == MVT::i32)
4414 return std::make_pair(ABI.getTempReg(9, false).id(),
4415 &Mips::GPR32RegClass);
4416 if (VT == MVT::i64)
4417 return std::make_pair(ABI.getTempReg(9, true).id(),
4418 &Mips::GPR64RegClass);
4419 // This will generate an error message
4420 return std::make_pair(0U, nullptr);
4421 case 'l': // use the `lo` register to store values
4422 // that are no bigger than a word
4423 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8)
4424 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
4425 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
4426 case 'x': // use the concatenated `hi` and `lo` registers
4427 // to store doubleword values
4428 // Fixme: Not triggering the use of both hi and low
4429 // This will generate an error message
4430 return std::make_pair(0U, nullptr);
4431 }
4432 }
4433
4434 if (!Constraint.empty()) {
4435 std::pair<unsigned, const TargetRegisterClass *> R;
4436 R = parseRegForInlineAsmConstraint(Constraint, VT);
4437
4438 if (R.second)
4439 return R;
4440 }
4441
4442 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4443}
4444
4445/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4446/// vector. If it is invalid, don't add anything to Ops.
4447void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
4448 StringRef Constraint,
4449 std::vector<SDValue> &Ops,
4450 SelectionDAG &DAG) const {
4451 SDLoc DL(Op);
4452 SDValue Result;
4453
4454 // Only support length 1 constraints for now.
4455 if (Constraint.size() > 1)
4456 return;
4457
4458 char ConstraintLetter = Constraint[0];
4459 switch (ConstraintLetter) {
4460 default: break; // This will fall through to the generic implementation
4461 case 'I': // Signed 16 bit constant
4462 // If this fails, the parent routine will give an error
4463 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4464 EVT Type = Op.getValueType();
4465 int64_t Val = C->getSExtValue();
4466 if (isInt<16>(Val)) {
4468 break;
4469 }
4470 }
4471 return;
4472 case 'J': // integer zero
4473 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4474 EVT Type = Op.getValueType();
4475 int64_t Val = C->getZExtValue();
4476 if (Val == 0) {
4477 Result = DAG.getTargetConstant(0, DL, Type);
4478 break;
4479 }
4480 }
4481 return;
4482 case 'K': // unsigned 16 bit immediate
4483 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4484 EVT Type = Op.getValueType();
4485 uint64_t Val = C->getZExtValue();
4486 if (isUInt<16>(Val)) {
4487 Result = DAG.getTargetConstant(Val, DL, Type);
4488 break;
4489 }
4490 }
4491 return;
4492 case 'L': // signed 32 bit immediate where lower 16 bits are 0
4493 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4494 EVT Type = Op.getValueType();
4495 int64_t Val = C->getSExtValue();
4496 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
4498 break;
4499 }
4500 }
4501 return;
4502 case 'N': // immediate in the range of -65535 to -1 (inclusive)
4503 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4504 EVT Type = Op.getValueType();
4505 int64_t Val = C->getSExtValue();
4506 if ((Val >= -65535) && (Val <= -1)) {
4508 break;
4509 }
4510 }
4511 return;
4512 case 'O': // signed 15 bit immediate
4513 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4514 EVT Type = Op.getValueType();
4515 int64_t Val = C->getSExtValue();
4516 if ((isInt<15>(Val))) {
4518 break;
4519 }
4520 }
4521 return;
4522 case 'P': // immediate in the range of 1 to 65535 (inclusive)
4523 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4524 EVT Type = Op.getValueType();
4525 int64_t Val = C->getSExtValue();
4526 if ((Val <= 65535) && (Val >= 1)) {
4527 Result = DAG.getTargetConstant(Val, DL, Type);
4528 break;
4529 }
4530 }
4531 return;
4532 }
4533
4534 if (Result.getNode()) {
4535 Ops.push_back(Result);
4536 return;
4537 }
4538
4540}
4541
4542bool MipsTargetLowering::isLegalAddressingMode(const DataLayout &DL,
4543 const AddrMode &AM, Type *Ty,
4544 unsigned AS,
4545 Instruction *I) const {
4546 // No global is ever allowed as a base.
4547 if (AM.BaseGV)
4548 return false;
4549
4550 switch (AM.Scale) {
4551 case 0: // "r+i" or just "i", depending on HasBaseReg.
4552 break;
4553 case 1:
4554 if (!AM.HasBaseReg) // allow "r+i".
4555 break;
4556 return false; // disallow "r+r" or "r+r+i".
4557 default:
4558 return false;
4559 }
4560
4561 return true;
4562}
4563
4564bool
4565MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4566 // The Mips target isn't yet aware of offsets.
4567 return false;
4568}
4569
4570EVT MipsTargetLowering::getOptimalMemOpType(
4571 LLVMContext &Context, const MemOp &Op,
4572 const AttributeList &FuncAttributes) const {
4573 if (Subtarget.hasMips64())
4574 return MVT::i64;
4575
4576 return MVT::i32;
4577}
4578
4579bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
4580 bool ForCodeSize) const {
4581 if (VT != MVT::f32 && VT != MVT::f64)
4582 return false;
4583 if (Imm.isNegZero())
4584 return false;
4585 return Imm.isZero();
4586}
4587
4588bool MipsTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
4589 return isInt<16>(Imm);
4590}
4591
4592bool MipsTargetLowering::isLegalAddImmediate(int64_t Imm) const {
4593 return isInt<16>(Imm);
4594}
4595
4597 if (!isPositionIndependent())
4599 if (ABI.IsN64())
4602}
4603
4604SDValue MipsTargetLowering::getPICJumpTableRelocBase(SDValue Table,
4605 SelectionDAG &DAG) const {
4606 if (!isPositionIndependent())
4607 return Table;
4609}
4610
4612 return Subtarget.useSoftFloat();
4613}
4614
4615void MipsTargetLowering::copyByValRegs(
4616 SDValue Chain, const SDLoc &DL, std::vector<SDValue> &OutChains,
4617 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
4618 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
4619 unsigned FirstReg, unsigned LastReg, const CCValAssign &VA,
4620 MipsCCState &State) const {
4622 MachineFrameInfo &MFI = MF.getFrameInfo();
4623 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
4624 unsigned NumRegs = LastReg - FirstReg;
4625 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
4626 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
4627 int FrameObjOffset;
4628 ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
4629
4630 if (RegAreaSize)
4631 FrameObjOffset =
4632 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
4633 (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
4634 else
4635 FrameObjOffset = VA.getLocMemOffset();
4636
4637 // Create frame object.
4638 EVT PtrTy = getPointerTy(DAG.getDataLayout());
4639 // Make the fixed object stored to mutable so that the load instructions
4640 // referencing it have their memory dependencies added.
4641 // Set the frame object as isAliased which clears the underlying objects
4642 // vector in ScheduleDAGInstrs::buildSchedGraph() resulting in addition of all
4643 // stores as dependencies for loads referencing this fixed object.
4644 int FI = MFI.CreateFixedObject(FrameObjSize, FrameObjOffset, false, true);
4645 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4646 InVals.push_back(FIN);
4647
4648 if (!NumRegs)
4649 return;
4650
4651 // Copy arg registers.
4652 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
4653 const TargetRegisterClass *RC = getRegClassFor(RegTy);
4654
4655 for (unsigned I = 0; I < NumRegs; ++I) {
4656 unsigned ArgReg = ByValArgRegs[FirstReg + I];
4657 unsigned VReg = addLiveIn(MF, ArgReg, RC);
4658 unsigned Offset = I * GPRSizeInBytes;
4659 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
4660 DAG.getConstant(Offset, DL, PtrTy));
4661 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
4662 StorePtr, MachinePointerInfo(FuncArg, Offset));
4663 OutChains.push_back(Store);
4664 }
4665}
4666
4667// Copy byVal arg to registers and stack.
4668void MipsTargetLowering::passByValArg(
4669 SDValue Chain, const SDLoc &DL,
4670 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
4671 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
4672 MachineFrameInfo &MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
4673 unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
4674 const CCValAssign &VA) const {
4675 unsigned ByValSizeInBytes = Flags.getByValSize();
4676 unsigned OffsetInBytes = 0; // From beginning of struct
4677 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4679 std::min(Flags.getNonZeroByValAlign(), Align(RegSizeInBytes));
4680 EVT PtrTy = getPointerTy(DAG.getDataLayout()),
4681 RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4682 unsigned NumRegs = LastReg - FirstReg;
4683
4684 if (NumRegs) {
4685 ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs();
4686 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
4687 unsigned I = 0;
4688
4689 // Copy words to registers.
4690 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
4691 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4692 DAG.getConstant(OffsetInBytes, DL, PtrTy));
4693 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
4694 MachinePointerInfo(), Alignment);
4695 MemOpChains.push_back(LoadVal.getValue(1));
4696 unsigned ArgReg = ArgRegs[FirstReg + I];
4697 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
4698 }
4699
4700 // Return if the struct has been fully copied.
4701 if (ByValSizeInBytes == OffsetInBytes)
4702 return;
4703
4704 // Copy the remainder of the byval argument with sub-word loads and shifts.
4705 if (LeftoverBytes) {
4706 SDValue Val;
4707
4708 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
4709 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
4710 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
4711
4712 if (RemainingSizeInBytes < LoadSizeInBytes)
4713 continue;
4714
4715 // Load subword.
4716 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4717 DAG.getConstant(OffsetInBytes, DL,
4718 PtrTy));
4719 SDValue LoadVal = DAG.getExtLoad(
4720 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
4721 MVT::getIntegerVT(LoadSizeInBytes * 8), Alignment);
4722 MemOpChains.push_back(LoadVal.getValue(1));
4723
4724 // Shift the loaded value.
4725 unsigned Shamt;
4726
4727 if (isLittle)
4728 Shamt = TotalBytesLoaded * 8;
4729 else
4730 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
4731
4732 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
4733 DAG.getConstant(Shamt, DL, MVT::i32));
4734
4735 if (Val.getNode())
4736 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
4737 else
4738 Val = Shift;
4739
4740 OffsetInBytes += LoadSizeInBytes;
4741 TotalBytesLoaded += LoadSizeInBytes;
4742 Alignment = std::min(Alignment, Align(LoadSizeInBytes));
4743 }
4744
4745 unsigned ArgReg = ArgRegs[FirstReg + I];
4746 RegsToPass.push_back(std::make_pair(ArgReg, Val));
4747 return;
4748 }
4749 }
4750
4751 // Copy remainder of byval arg to it with memcpy.
4752 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
4753 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4754 DAG.getConstant(OffsetInBytes, DL, PtrTy));
4755 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
4757 Chain = DAG.getMemcpy(
4758 Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, DL, PtrTy), Alignment,
4759 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
4760 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(), MachinePointerInfo());
4761 MemOpChains.push_back(Chain);
4762}
4763
4764void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
4765 SDValue Chain, const SDLoc &DL,
4766 SelectionDAG &DAG,
4767 CCState &State) const {
4768 ArrayRef<MCPhysReg> ArgRegs = ABI.getVarArgRegs(Subtarget.isGP64bit());
4769 unsigned Idx = State.getFirstUnallocated(ArgRegs);
4770 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4771 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4772 const TargetRegisterClass *RC = getRegClassFor(RegTy);
4774 MachineFrameInfo &MFI = MF.getFrameInfo();
4775 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4776
4777 // Offset of the first variable argument from stack pointer.
4778 int VaArgOffset;
4779
4780 if (ArgRegs.size() == Idx)
4781 VaArgOffset = alignTo(State.getStackSize(), RegSizeInBytes);
4782 else {
4783 VaArgOffset =
4784 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
4785 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
4786 }
4787
4788 // Record the frame index of the first variable argument
4789 // which is a value necessary to VASTART.
4790 int FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4791 MipsFI->setVarArgsFrameIndex(FI);
4792
4793 // Copy the integer registers that have not been used for argument passing
4794 // to the argument register save area. For O32, the save area is allocated
4795 // in the caller's stack frame, while for N32/64, it is allocated in the
4796 // callee's stack frame.
4797 for (unsigned I = Idx; I < ArgRegs.size();
4798 ++I, VaArgOffset += RegSizeInBytes) {
4799 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
4800 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
4801 FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4802 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4803 SDValue Store =
4804 DAG.getStore(Chain, DL, ArgValue, PtrOff, MachinePointerInfo());
4805 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
4806 (Value *)nullptr);
4807 OutChains.push_back(Store);
4808 }
4809}
4810
4812 Align Alignment) const {
4813 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
4814
4815 assert(Size && "Byval argument's size shouldn't be 0.");
4816
4817 Alignment = std::min(Alignment, TFL->getStackAlign());
4818
4819 unsigned FirstReg = 0;
4820 unsigned NumRegs = 0;
4821
4822 if (State->getCallingConv() != CallingConv::Fast) {
4823 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4824 ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
4825 // FIXME: The O32 case actually describes no shadow registers.
4826 const MCPhysReg *ShadowRegs =
4827 ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
4828
4829 // We used to check the size as well but we can't do that anymore since
4830 // CCState::HandleByVal() rounds up the size after calling this function.
4831 assert(
4832 Alignment >= Align(RegSizeInBytes) &&
4833 "Byval argument's alignment should be a multiple of RegSizeInBytes.");
4834
4835 FirstReg = State->getFirstUnallocated(IntArgRegs);
4836
4837 // If Alignment > RegSizeInBytes, the first arg register must be even.
4838 // FIXME: This condition happens to do the right thing but it's not the
4839 // right way to test it. We want to check that the stack frame offset
4840 // of the register is aligned.
4841 if ((Alignment > RegSizeInBytes) && (FirstReg % 2)) {
4842 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
4843 ++FirstReg;
4844 }
4845
4846 // Mark the registers allocated.
4847 Size = alignTo(Size, RegSizeInBytes);
4848 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
4849 Size -= RegSizeInBytes, ++I, ++NumRegs)
4850 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
4851 }
4852
4853 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
4854}
4855
4856MachineBasicBlock *MipsTargetLowering::emitPseudoSELECT(MachineInstr &MI,
4858 bool isFPCmp,
4859 unsigned Opc) const {
4861 "Subtarget already supports SELECT nodes with the use of"
4862 "conditional-move instructions.");
4863
4864 const TargetInstrInfo *TII =
4866 DebugLoc DL = MI.getDebugLoc();
4867
4868 // To "insert" a SELECT instruction, we actually have to insert the
4869 // diamond control-flow pattern. The incoming instruction knows the
4870 // destination vreg to set, the condition code register to branch on, the
4871 // true/false values to select between, and a branch opcode to use.
4872 const BasicBlock *LLVM_BB = BB->getBasicBlock();
4874
4875 // thisMBB:
4876 // ...
4877 // TrueVal = ...
4878 // setcc r1, r2, r3
4879 // bNE r1, r0, copy1MBB
4880 // fallthrough --> copy0MBB
4881 MachineBasicBlock *thisMBB = BB;
4882 MachineFunction *F = BB->getParent();
4883 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4884 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
4885 F->insert(It, copy0MBB);
4886 F->insert(It, sinkMBB);
4887
4888 // Transfer the remainder of BB and its successor edges to sinkMBB.
4889 sinkMBB->splice(sinkMBB->begin(), BB,
4890 std::next(MachineBasicBlock::iterator(MI)), BB->end());
4892
4893 // Next, add the true and fallthrough blocks as its successors.
4894 BB->addSuccessor(copy0MBB);
4895 BB->addSuccessor(sinkMBB);
4896
4897 if (isFPCmp) {
4898 // bc1[tf] cc, sinkMBB
4899 BuildMI(BB, DL, TII->get(Opc))
4900 .addReg(MI.getOperand(1).getReg())
4901 .addMBB(sinkMBB);
4902 } else {
4903 // bne rs, $0, sinkMBB
4904 BuildMI(BB, DL, TII->get(Opc))
4905 .addReg(MI.getOperand(1).getReg())
4906 .addReg(Mips::ZERO)
4907 .addMBB(sinkMBB);
4908 }
4909
4910 // copy0MBB:
4911 // %FalseValue = ...
4912 // # fallthrough to sinkMBB
4913 BB = copy0MBB;
4914
4915 // Update machine-CFG edges
4916 BB->addSuccessor(sinkMBB);
4917
4918 // sinkMBB:
4919 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
4920 // ...
4921 BB = sinkMBB;
4922
4923 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(0).getReg())
4924 .addReg(MI.getOperand(2).getReg())
4925 .addMBB(thisMBB)
4926 .addReg(MI.getOperand(3).getReg())
4927 .addMBB(copy0MBB);
4928
4929 MI.eraseFromParent(); // The pseudo instruction is gone now.
4930
4931 return BB;
4932}
4933
4935MipsTargetLowering::emitPseudoD_SELECT(MachineInstr &MI,
4936 MachineBasicBlock *BB) const {
4937 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
4938 "Subtarget already supports SELECT nodes with the use of"
4939 "conditional-move instructions.");
4940
4941 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
4942 DebugLoc DL = MI.getDebugLoc();
4943
4944 // D_SELECT substitutes two SELECT nodes that goes one after another and
4945 // have the same condition operand. On machines which don't have
4946 // conditional-move instruction, it reduces unnecessary branch instructions
4947 // which are result of using two diamond patterns that are result of two
4948 // SELECT pseudo instructions.
4949 const BasicBlock *LLVM_BB = BB->getBasicBlock();
4951
4952 // thisMBB:
4953 // ...
4954 // TrueVal = ...
4955 // setcc r1, r2, r3
4956 // bNE r1, r0, copy1MBB
4957 // fallthrough --> copy0MBB
4958 MachineBasicBlock *thisMBB = BB;
4959 MachineFunction *F = BB->getParent();
4960 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4961 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
4962 F->insert(It, copy0MBB);
4963 F->insert(It, sinkMBB);
4964
4965 // Transfer the remainder of BB and its successor edges to sinkMBB.
4966 sinkMBB->splice(sinkMBB->begin(), BB,
4967 std::next(MachineBasicBlock::iterator(MI)), BB->end());
4969
4970 // Next, add the true and fallthrough blocks as its successors.
4971 BB->addSuccessor(copy0MBB);
4972 BB->addSuccessor(sinkMBB);
4973
4974 // bne rs, $0, sinkMBB
4975 BuildMI(BB, DL, TII->get(Mips::BNE))
4976 .addReg(MI.getOperand(2).getReg())
4977 .addReg(Mips::ZERO)
4978 .addMBB(sinkMBB);
4979
4980 // copy0MBB:
4981 // %FalseValue = ...
4982 // # fallthrough to sinkMBB
4983 BB = copy0MBB;
4984
4985 // Update machine-CFG edges
4986 BB->addSuccessor(sinkMBB);
4987
4988 // sinkMBB:
4989 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
4990 // ...
4991 BB = sinkMBB;
4992
4993 // Use two PHI nodes to select two reults
4994 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(0).getReg())
4995 .addReg(MI.getOperand(3).getReg())
4996 .addMBB(thisMBB)
4997 .addReg(MI.getOperand(5).getReg())
4998 .addMBB(copy0MBB);
4999 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(1).getReg())
5000 .addReg(MI.getOperand(4).getReg())
5001 .addMBB(thisMBB)
5002 .addReg(MI.getOperand(6).getReg())
5003 .addMBB(copy0MBB);
5004
5005 MI.eraseFromParent(); // The pseudo instruction is gone now.
5006
5007 return BB;
5008}
5009
5012 const MachineFunction &MF) const {
5013 StringRef Name(RegName);
5014 Name.consume_front("$");
5015
5016 unsigned RegIdx;
5017 if (Name.getAsInteger(10, RegIdx)) {
5018 std::string LowerName = Name.lower();
5019 const MCRegisterInfo &MRI = *MF.getContext().getRegisterInfo();
5020 int Index =
5021 MIPS_MC::getCPURegisterIndex(LowerName, MRI, ABI.getRegAltNameIndex());
5022 if (Index < 0)
5024 Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
5025 RegIdx = Index;
5026 }
5027
5028 if (RegIdx < 32) {
5029 const MCRegisterInfo *MRI = MF.getContext().getRegisterInfo();
5030 unsigned RegClassID = Mips::GPR32RegClassID;
5031 if (VT.isValid()) {
5032 if (VT.getSizeInBits() == 64) {
5033 if (!Subtarget.isGP64bit())
5034 report_fatal_error("64-bit registers not supported on 32-bit target");
5035 RegClassID = Mips::GPR64RegClassID;
5036 } else if (VT.getSizeInBits() == 32) {
5037 RegClassID = Mips::GPR32RegClassID;
5038 } else {
5039 report_fatal_error(Twine("Invalid register \"" + StringRef(RegName) +
5040 "\" for " + Twine(VT.getSizeInBits()) +
5041 "-bit type."));
5042 }
5043 } else if (Subtarget.isGP64bit()) {
5044 RegClassID = Mips::GPR64RegClassID;
5045 }
5046 const MCRegisterClass &RC = MRI->getRegClass(RegClassID);
5047 Register Reg = RC.getRegister(RegIdx);
5048 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
5049 if (!ReservedRegs.test(Reg))
5050 reportFatalUsageError(Twine("Trying to obtain non-reserved register \"" +
5051 StringRef(RegName) + "\"."));
5052 return Reg;
5053 }
5054
5056 Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
5057}
5058
5059MachineBasicBlock *MipsTargetLowering::emitLDR_W(MachineInstr &MI,
5060 MachineBasicBlock *BB) const {
5061 MachineFunction *MF = BB->getParent();
5062 MachineRegisterInfo &MRI = MF->getRegInfo();
5064 const bool IsLittle = Subtarget.isLittle();
5065 DebugLoc DL = MI.getDebugLoc();
5066
5067 Register Dest = MI.getOperand(0).getReg();
5068 Register Address = MI.getOperand(1).getReg();
5069 unsigned Imm = MI.getOperand(2).getImm();
5070
5072
5074 // Mips release 6 can load from adress that is not naturally-aligned.
5075 Register Temp = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5076 BuildMI(*BB, I, DL, TII->get(Mips::LW))
5077 .addDef(Temp)
5078 .addUse(Address)
5079 .addImm(Imm);
5080 BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Dest).addUse(Temp);
5081 } else {
5082 // Mips release 5 needs to use instructions that can load from an unaligned
5083 // memory address.
5084 Register LoadHalf = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5085 Register LoadFull = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5086 Register Undef = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5087 BuildMI(*BB, I, DL, TII->get(Mips::IMPLICIT_DEF)).addDef(Undef);
5088 BuildMI(*BB, I, DL, TII->get(Mips::LWR))
5089 .addDef(LoadHalf)
5090 .addUse(Address)
5091 .addImm(Imm + (IsLittle ? 0 : 3))
5092 .addUse(Undef);
5093 BuildMI(*BB, I, DL, TII->get(Mips::LWL))
5094 .addDef(LoadFull)
5095 .addUse(Address)
5096 .addImm(Imm + (IsLittle ? 3 : 0))
5097 .addUse(LoadHalf);
5098 BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Dest).addUse(LoadFull);
5099 }
5100
5101 MI.eraseFromParent();
5102 return BB;
5103}
5104
5105MachineBasicBlock *MipsTargetLowering::emitLDR_D(MachineInstr &MI,
5106 MachineBasicBlock *BB) const {
5107 MachineFunction *MF = BB->getParent();
5108 MachineRegisterInfo &MRI = MF->getRegInfo();
5109 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
5110 const bool IsLittle = Subtarget.isLittle();
5111 DebugLoc DL = MI.getDebugLoc();
5112
5113 Register Dest = MI.getOperand(0).getReg();
5114 Register Address = MI.getOperand(1).getReg();
5115 unsigned Imm = MI.getOperand(2).getImm();
5116
5118
5119 if (Subtarget.hasMips32r6() || Subtarget.hasMips64r6()) {
5120 // Mips release 6 can load from adress that is not naturally-aligned.
5121 if (Subtarget.isGP64bit()) {
5122 Register Temp = MRI.createVirtualRegister(&Mips::GPR64RegClass);
5123 BuildMI(*BB, I, DL, TII->get(Mips::LD))
5124 .addDef(Temp)
5125 .addUse(Address)
5126 .addImm(Imm);
5127 BuildMI(*BB, I, DL, TII->get(Mips::FILL_D)).addDef(Dest).addUse(Temp);
5128 } else {
5129 Register Wtemp = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
5130 Register Lo = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5131 Register Hi = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5132 BuildMI(*BB, I, DL, TII->get(Mips::LW))
5133 .addDef(Lo)
5134 .addUse(Address)
5135 .addImm(Imm + (IsLittle ? 0 : 4));
5136 BuildMI(*BB, I, DL, TII->get(Mips::LW))
5137 .addDef(Hi)
5138 .addUse(Address)
5139 .addImm(Imm + (IsLittle ? 4 : 0));
5140 BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Wtemp).addUse(Lo);
5141 BuildMI(*BB, I, DL, TII->get(Mips::INSERT_W), Dest)
5142 .addUse(Wtemp)
5143 .addUse(Hi)
5144 .addImm(1);
5145 }
5146 } else {
5147 // Mips release 5 needs to use instructions that can load from an unaligned
5148 // memory address.
5149 Register LoHalf = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5150 Register LoFull = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5151 Register LoUndef = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5152 Register HiHalf = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5153 Register HiFull = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5154 Register HiUndef = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5155 Register Wtemp = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
5156 BuildMI(*BB, I, DL, TII->get(Mips::IMPLICIT_DEF)).addDef(LoUndef);
5157 BuildMI(*BB, I, DL, TII->get(Mips::LWR))
5158 .addDef(LoHalf)
5159 .addUse(Address)
5160 .addImm(Imm + (IsLittle ? 0 : 7))
5161 .addUse(LoUndef);
5162 BuildMI(*BB, I, DL, TII->get(Mips::LWL))
5163 .addDef(LoFull)
5164 .addUse(Address)
5165 .addImm(Imm + (IsLittle ? 3 : 4))
5166 .addUse(LoHalf);
5167 BuildMI(*BB, I, DL, TII->get(Mips::IMPLICIT_DEF)).addDef(HiUndef);
5168 BuildMI(*BB, I, DL, TII->get(Mips::LWR))
5169 .addDef(HiHalf)
5170 .addUse(Address)
5171 .addImm(Imm + (IsLittle ? 4 : 3))
5172 .addUse(HiUndef);
5173 BuildMI(*BB, I, DL, TII->get(Mips::LWL))
5174 .addDef(HiFull)
5175 .addUse(Address)
5176 .addImm(Imm + (IsLittle ? 7 : 0))
5177 .addUse(HiHalf);
5178 BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Wtemp).addUse(LoFull);
5179 BuildMI(*BB, I, DL, TII->get(Mips::INSERT_W), Dest)
5180 .addUse(Wtemp)
5181 .addUse(HiFull)
5182 .addImm(1);
5183 }
5184
5185 MI.eraseFromParent();
5186 return BB;
5187}
5188
5189MachineBasicBlock *MipsTargetLowering::emitSTR_W(MachineInstr &MI,
5190 MachineBasicBlock *BB) const {
5191 MachineFunction *MF = BB->getParent();
5192 MachineRegisterInfo &MRI = MF->getRegInfo();
5193 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
5194 const bool IsLittle = Subtarget.isLittle();
5195 DebugLoc DL = MI.getDebugLoc();
5196
5197 Register StoreVal = MI.getOperand(0).getReg();
5198 Register Address = MI.getOperand(1).getReg();
5199 unsigned Imm = MI.getOperand(2).getImm();
5200
5202
5203 if (Subtarget.hasMips32r6() || Subtarget.hasMips64r6()) {
5204 // Mips release 6 can store to adress that is not naturally-aligned.
5205 Register BitcastW = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
5206 Register Tmp = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5207 BuildMI(*BB, I, DL, TII->get(Mips::COPY)).addDef(BitcastW).addUse(StoreVal);
5208 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
5209 .addDef(Tmp)
5210 .addUse(BitcastW)
5211 .addImm(0);
5212 BuildMI(*BB, I, DL, TII->get(Mips::SW))
5213 .addUse(Tmp)
5214 .addUse(Address)
5215 .addImm(Imm);
5216 } else {
5217 // Mips release 5 needs to use instructions that can store to an unaligned
5218 // memory address.
5219 Register Tmp = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5220 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
5221 .addDef(Tmp)
5222 .addUse(StoreVal)
5223 .addImm(0);
5224 BuildMI(*BB, I, DL, TII->get(Mips::SWR))
5225 .addUse(Tmp)
5226 .addUse(Address)
5227 .addImm(Imm + (IsLittle ? 0 : 3));
5228 BuildMI(*BB, I, DL, TII->get(Mips::SWL))
5229 .addUse(Tmp)
5230 .addUse(Address)
5231 .addImm(Imm + (IsLittle ? 3 : 0));
5232 }
5233
5234 MI.eraseFromParent();
5235
5236 return BB;
5237}
5238
5239MachineBasicBlock *MipsTargetLowering::emitSTR_D(MachineInstr &MI,
5240 MachineBasicBlock *BB) const {
5241 MachineFunction *MF = BB->getParent();
5242 MachineRegisterInfo &MRI = MF->getRegInfo();
5243 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
5244 const bool IsLittle = Subtarget.isLittle();
5245 DebugLoc DL = MI.getDebugLoc();
5246
5247 Register StoreVal = MI.getOperand(0).getReg();
5248 Register Address = MI.getOperand(1).getReg();
5249 unsigned Imm = MI.getOperand(2).getImm();
5250
5252
5253 if (Subtarget.hasMips32r6() || Subtarget.hasMips64r6()) {
5254 // Mips release 6 can store to adress that is not naturally-aligned.
5255 if (Subtarget.isGP64bit()) {
5256 Register BitcastD = MRI.createVirtualRegister(&Mips::MSA128DRegClass);
5257 Register Lo = MRI.createVirtualRegister(&Mips::GPR64RegClass);
5258 BuildMI(*BB, I, DL, TII->get(Mips::COPY))
5259 .addDef(BitcastD)
5260 .addUse(StoreVal);
5261 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_D))
5262 .addDef(Lo)
5263 .addUse(BitcastD)
5264 .addImm(0);
5265 BuildMI(*BB, I, DL, TII->get(Mips::SD))
5266 .addUse(Lo)
5267 .addUse(Address)
5268 .addImm(Imm);
5269 } else {
5270 Register BitcastW = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
5271 Register Lo = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5272 Register Hi = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5273 BuildMI(*BB, I, DL, TII->get(Mips::COPY))
5274 .addDef(BitcastW)
5275 .addUse(StoreVal);
5276 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
5277 .addDef(Lo)
5278 .addUse(BitcastW)
5279 .addImm(0);
5280 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
5281 .addDef(Hi)
5282 .addUse(BitcastW)
5283 .addImm(1);
5284 BuildMI(*BB, I, DL, TII->get(Mips::SW))
5285 .addUse(Lo)
5286 .addUse(Address)
5287 .addImm(Imm + (IsLittle ? 0 : 4));
5288 BuildMI(*BB, I, DL, TII->get(Mips::SW))
5289 .addUse(Hi)
5290 .addUse(Address)
5291 .addImm(Imm + (IsLittle ? 4 : 0));
5292 }
5293 } else {
5294 // Mips release 5 needs to use instructions that can store to an unaligned
5295 // memory address.
5296 Register Bitcast = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
5297 Register Lo = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5298 Register Hi = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5299 BuildMI(*BB, I, DL, TII->get(Mips::COPY)).addDef(Bitcast).addUse(StoreVal);
5300 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
5301 .addDef(Lo)
5302 .addUse(Bitcast)
5303 .addImm(0);
5304 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
5305 .addDef(Hi)
5306 .addUse(Bitcast)
5307 .addImm(1);
5308 BuildMI(*BB, I, DL, TII->get(Mips::SWR))
5309 .addUse(Lo)
5310 .addUse(Address)
5311 .addImm(Imm + (IsLittle ? 0 : 3));
5312 BuildMI(*BB, I, DL, TII->get(Mips::SWL))
5313 .addUse(Lo)
5314 .addUse(Address)
5315 .addImm(Imm + (IsLittle ? 3 : 0));
5316 BuildMI(*BB, I, DL, TII->get(Mips::SWR))
5317 .addUse(Hi)
5318 .addUse(Address)
5319 .addImm(Imm + (IsLittle ? 4 : 7));
5320 BuildMI(*BB, I, DL, TII->get(Mips::SWL))
5321 .addUse(Hi)
5322 .addUse(Address)
5323 .addImm(Imm + (IsLittle ? 7 : 4));
5324 }
5325
5326 MI.eraseFromParent();
5327 return BB;
5328}
static SDValue performSHLCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG)
If the operand is a bitwise AND with a constant RHS, and the shift has a constant RHS and is the only...
static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
static SDValue performANDCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned Imm
unsigned uint64_t
This file declares a class to represent arbitrary precision floating point values and provide a varie...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
static LVOptions Options
Definition LVOptions.cpp:25
lazy value info
static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static MachineBasicBlock * insertDivByZeroTrap(MachineInstr &MI, MachineBasicBlock *MBB)
static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
cl::opt< bool > EmitJalrReloc
cl::opt< bool > NoZeroDivCheck
static bool CC_Mips(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
static SDValue performMADD_MSUBCombine(SDNode *ROOTNode, SelectionDAG &CurDAG, const MipsSubtarget &Subtarget)
static bool invertFPCondCodeUser(Mips::CondCode CC)
This function returns true if the floating point conditional branches and conditional moves which use...
static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State, ArrayRef< MCPhysReg > F64Regs)
static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG, bool SingleFloat)
static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const MipsSubtarget &Subtarget)
static const MCPhysReg Mips64DPRegs[8]
static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG, bool IsLittle)
static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD, SDValue Chain, unsigned Offset)
static unsigned addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
static std::pair< bool, bool > parsePhysicalReg(StringRef C, StringRef &Prefix, unsigned long long &Reg)
This is a helper function to parse a physical register string and split it into non-numeric and numer...
static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD, SDValue Chain, SDValue Src, unsigned Offset)
static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasExtractInsert)
static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op)
static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasExtractInsert)
DivByZeroTrapKind
static SDValue performSignExtendCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const MipsSubtarget &Subtarget)
static SDValue performCMovFPCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const MipsSubtarget &Subtarget)
static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA, EVT ArgVT, const SDLoc &DL, SelectionDAG &DAG)
static Mips::CondCode condCodeToFCC(ISD::CondCode CC)
static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True, SDValue False, const SDLoc &DL)
static cl::opt< bool > UseMipsTailCalls("mips-tail-calls", cl::Hidden, cl::desc("MIPS: permit tail calls."), cl::init(false))
uint64_t IntrinsicInst * II
const SmallVectorImpl< MachineOperand > & Cond
SI optimize exec mask operations pre RA
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:484
This file defines the SmallVector class.
static const MCPhysReg IntRegs[32]
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static const MCPhysReg F32Regs[64]
Value * RHS
Value * LHS
bool isZero() const
Definition APFloat.h:1579
APInt bitcastToAPInt() const
Definition APFloat.h:1475
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
LLVM_ABI APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
Definition APInt.cpp:478
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
const T * data() const
Definition ArrayRef.h:138
LLVM Basic Block Representation.
Definition BasicBlock.h:62
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
static constexpr BranchProbability getOne()
CCState - This class holds information needed while lowering arguments and return values.
unsigned getFirstUnallocated(ArrayRef< MCPhysReg > Regs) const
getFirstUnallocated - Return the index of the first unallocated register in the set,...
CallingConv::ID getCallingConv() const
uint64_t getStackSize() const
Returns the size of the currently allocated portion of the stack.
CCValAssign - Represent assignment of one arg/retval to a location.
Register getLocReg() const
LocInfo getLocInfo() const
static CCValAssign getReg(unsigned ValNo, MVT ValVT, MCRegister Reg, MVT LocVT, LocInfo HTP, bool IsCustom=false)
static CCValAssign getCustomReg(unsigned ValNo, MVT ValVT, MCRegister Reg, MVT LocVT, LocInfo HTP)
bool isUpperBitsInLoc() const
static CCValAssign getMem(unsigned ValNo, MVT ValVT, int64_t Offset, MVT LocVT, LocInfo HTP, bool IsCustom=false)
bool needsCustom() const
int64_t getLocMemOffset() const
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
const APFloat & getValueAPF() const
uint64_t getZExtValue() const
int64_t getSExtValue() const
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
A debug info location.
Definition DebugLoc.h:126
const char * getSymbol() const
This is a fast-path instruction selection class that generates poor code and doesn't support illegal ...
Definition FastISel.h:67
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
bool hasStructRetAttr() const
Determine if the function returns a structure through first or second pointer argument.
Definition Function.h:673
const Argument * const_arg_iterator
Definition Function.h:74
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:730
const GlobalValue * getGlobal() const
bool isDSOLocal() const
bool hasLocalLinkage() const
bool hasPrivateLinkage() const
bool hasHiddenVisibility() const
bool hasDLLImportStorageClass() const
bool isDeclarationForLinker() const
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:521
bool hasInternalLinkage() const
bool hasProtectedVisibility() const
constexpr bool isValid() const
constexpr TypeSize getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
Tracks which library functions to use for a particular subtarget or function.
This class is used to represent ISD::LOAD nodes.
const MCRegisterInfo * getRegisterInfo() const
Definition MCContext.h:411
LLVM_ABI MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
MCRegisterClass - Base class of TargetRegisterClass.
MCRegister getRegister(unsigned i) const
getRegister - Return the specified register in the class.
iterator begin() const
begin/end - Return all of the registers in this class.
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
const MCRegisterClass & getRegClass(unsigned i) const
Returns the register class associated with the enumeration value.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
Machine Value Type.
SimpleValueType SimpleTy
static auto integer_valuetypes()
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
static MVT getVectorVT(MVT VT, unsigned NumElements)
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
bool isValid() const
Return true if this is a valid simple valuetype.
static MVT getIntegerVT(unsigned BitWidth)
static auto fp_valuetypes()
static auto fp_fixedlen_vector_valuetypes()
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
LLVM_ABI int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
void setFrameAddressIsTaken(bool T)
void setHasTailCall(bool V=true)
void setReturnAddressIsTaken(bool s)
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MCContext & getContext() const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC)
addLiveIn - Add the specified physical register as a live-in value and create a corresponding virtual...
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
Representation of each machine instruction.
const MachineOperand & getOperand(unsigned i) const
@ EK_GPRel32BlockAddress
EK_GPRel32BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative,...
@ EK_BlockAddress
EK_BlockAddress - Each entry is a plain address of block, e.g.: .word LBB123.
@ EK_GPRel64BlockAddress
EK_GPRel64BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative,...
@ MOVolatile
The memory access is volatile.
Flags getFlags() const
Return the raw flags of the source value,.
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
static MachineOperand CreateMCSymbol(MCSymbol *Sym, unsigned TargetFlags=0)
void setIsKill(bool Val=true)
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
void addLiveIn(MCRegister Reg, Register vreg=Register())
addLiveIn - Add the specified register as a live-in.
Align getAlign() const
MachineMemOperand * getMemOperand() const
Return the unique MachineMemOperand object describing the memory reference performed by operation.
const MachinePointerInfo & getPointerInfo() const
const SDValue & getChain() const
EVT getMemoryVT() const
Return the type of the in-memory value.
static SpecialCallingConvType getSpecialCallingConvForCallee(const SDNode *Callee, const MipsSubtarget &Subtarget)
Determine the SpecialCallingConvType for the given callee.
MipsFunctionInfo - This class is derived from MachineFunction private Mips target-specific informatio...
void setVarArgsFrameIndex(int Index)
unsigned getSRetReturnReg() const
MachinePointerInfo callPtrInfo(MachineFunction &MF, const char *ES)
Create a MachinePointerInfo that has an ExternalSymbolPseudoSourceValue object representing a GOT ent...
Register getGlobalBaseReg(MachineFunction &MF)
void setSRetReturnReg(unsigned Reg)
void setFormalArgInfo(unsigned Size, bool HasByval)
static const uint32_t * getMips16RetHelperMask()
bool hasMips32r6() const
bool hasMips4() const
bool hasMips64r2() const
bool isLittle() const
const MipsInstrInfo * getInstrInfo() const override
bool hasMips64r6() const
bool inMips16Mode() const
bool hasMips64() const
bool hasMips32() const
const MipsRegisterInfo * getRegisterInfo() const override
bool hasCnMips() const
bool isGP64bit() const
bool hasExtractInsert() const
Features related to the presence of specific instructions.
bool isSingleFloat() const
const MipsABIInfo & getABI() const
const TargetFrameLowering * getFrameLowering() const override
MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const override
Return the register type for a given MVT, ensuring vectors are treated as a series of gpr sized integ...
bool hasBitTest(SDValue X, SDValue Y) const override
Return true if the target has a bit-test instruction: (X & (1 << Y)) ==/!= 0 This knowledge can be us...
static const MipsTargetLowering * create(const MipsTargetMachine &TM, const MipsSubtarget &STI)
SDValue getAddrGPRel(NodeTy *N, const SDLoc &DL, EVT Ty, SelectionDAG &DAG, bool IsN64) const
unsigned getVectorTypeBreakdownForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const override
Break down vectors to the correct number of gpr sized integers.
Register getRegisterByName(const char *RegName, LLT VT, const MachineFunction &MF) const override
Return the register ID of the name passed in.
SDValue getAddrNonPICSym64(NodeTy *N, const SDLoc &DL, EVT Ty, SelectionDAG &DAG) const
EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const override
getSetCCResultType - get the ISD::SETCC result ValueType
SDValue getAddrGlobal(NodeTy *N, const SDLoc &DL, EVT Ty, SelectionDAG &DAG, unsigned Flag, SDValue Chain, const MachinePointerInfo &PtrInfo) const
MipsTargetLowering(const MipsTargetMachine &TM, const MipsSubtarget &STI)
const MipsABIInfo & ABI
SDValue getAddrGlobalLargeGOT(NodeTy *N, const SDLoc &DL, EVT Ty, SelectionDAG &DAG, unsigned HiFlag, unsigned LoFlag, SDValue Chain, const MachinePointerInfo &PtrInfo) const
SDValue getDllimportVariable(NodeTy *N, const SDLoc &DL, EVT Ty, SelectionDAG &DAG, SDValue Chain, const MachinePointerInfo &PtrInfo) const
bool shouldFoldConstantShiftPairToMask(const SDNode *N) const override
Return true if it is profitable to fold a pair of shifts into a mask.
SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override
This method will be invoked for all target nodes and for any target-independent nodes that the target...
CCAssignFn * CCAssignFnForReturn() const
void ReplaceNodeResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const override
ReplaceNodeResults - Replace the results of node with an illegal result type with new values built ou...
MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const override
This method should be implemented by targets that mark instructions with the 'usesCustomInserter' fla...
SDValue getDllimportSymbol(NodeTy *N, const SDLoc &DL, EVT Ty, SelectionDAG &DAG) const
CCAssignFn * CCAssignFnForCall() const
unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const override
Return the number of registers for a given MVT, ensuring vectors are treated as a series of gpr sized...
SDValue getAddrNonPIC(NodeTy *N, const SDLoc &DL, EVT Ty, SelectionDAG &DAG) const
SDValue lowerSTORE(SDValue Op, SelectionDAG &DAG) const
FastISel * createFastISel(FunctionLoweringInfo &funcInfo, const TargetLibraryInfo *libInfo, const LibcallLoweringInfo *libcallLowering) const override
createFastISel - This method returns a target specific FastISel object, or null if the target does no...
void AdjustInstrPostInstrSelection(MachineInstr &MI, SDNode *Node) const override
This method should be implemented by targets that mark instructions with the 'hasPostISelHook' flag.
virtual void getOpndList(SmallVectorImpl< SDValue > &Ops, std::deque< std::pair< unsigned, SDValue > > &RegsToPass, bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage, bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const
This function fills Ops, which is the list of operands that will later be used when a function call n...
EVT getTypeForExtReturn(LLVMContext &Context, EVT VT, ISD::NodeType) const override
Return the type that should be used to zero or sign extend a zeroext/signext integer return value.
bool isCheapToSpeculateCtlz(Type *Ty) const override
Return true if it is cheap to speculate a call to intrinsic ctlz.
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override
LowerOperation - Provide custom lowering hooks for some operations.
bool isCheapToSpeculateCttz(Type *Ty) const override
Return true if it is cheap to speculate a call to intrinsic cttz.
SDValue getAddrLocal(NodeTy *N, const SDLoc &DL, EVT Ty, SelectionDAG &DAG, bool IsN32OrN64) const
SDValue getGlobalReg(SelectionDAG &DAG, EVT Ty) const
const MipsSubtarget & Subtarget
void HandleByVal(CCState *, unsigned &, Align) const override
Target-specific cleanup for formal ByVal parameters.
SDValue lowerLOAD(SDValue Op, SelectionDAG &DAG) const
bool IsConstantInSmallSection(const DataLayout &DL, const Constant *CN, const Function *F) const
Return true if this constant should be placed into small data section.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
const SDValue & getOperand(unsigned Num) const
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
unsigned getOpcode() const
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg, SDValue N)
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
SDValue getGLOBAL_OFFSET_TABLE(EVT VT)
Return a GLOBAL_OFFSET_TABLE node. This does not have a useful SDLoc.
LLVM_ABI SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef< SDValue > Ops, EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MOLoad|MachineMemOperand::MOStore, LocationSize Size=LocationSize::precise(0), const AAMDNodes &AAInfo=AAMDNodes())
Creates a MemIntrinsicNode that may produce a result and takes a list of operands.
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false, SDNodeFlags Flags={})
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
LLVM_ABI SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
SDValue getTargetJumpTable(int JTI, EVT VT, unsigned TargetFlags=0)
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2, SDValue InGlue, const SDLoc &DL)
Return a new CALLSEQ_END node, which always must have a glue result (to ensure it's not CSE'd).
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
const DataLayout & getDataLayout() const
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
SDValue getSignedTargetConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize, const SDLoc &DL)
Return a new CALLSEQ_START node, that starts new call frame, in which InSize bytes are set up inside ...
SDValue getSelectCC(const SDLoc &DL, SDValue LHS, SDValue RHS, SDValue True, SDValue False, ISD::CondCode Cond, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build SelectCC's if you just have an ISD::CondCode instead of an...
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI bool isKnownNeverNaN(SDValue Op, const APInt &DemandedElts, bool SNaN=false, unsigned Depth=0) const
Test whether the given SDValue (or all elements of it, if it is a vector) is known to never be NaN in...
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
SDValue getTargetBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, unsigned TargetFlags=0)
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI SDValue getRegisterMask(const uint32_t *RegMask)
void addCallSiteInfo(const SDNode *Node, CallSiteInfo &&CallInfo)
Set CallSiteInfo to be associated with Node.
LLVMContext * getContext() const
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
SDValue getTargetConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offset=0, unsigned TargetFlags=0)
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
LLVM_ABI std::pair< SDValue, SDValue > SplitScalar(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the scalar node with EXTRACT_ELEMENT using the provided VTs and return the low/high part.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class is used to represent ISD::STORE nodes.
const SDValue & getBasePtr() const
const SDValue & getValue() const
bool isTruncatingStore() const
Return true if the op does a truncation before store.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
const char * const_iterator
Definition StringRef.h:61
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
Information about stack frame layout on the target.
unsigned getStackAlignment() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
TargetInstrInfo - Interface to description of machine instruction set.
Provides information about what library functions are available for the current target.
void setBooleanVectorContents(BooleanContent Ty)
Specify how the target extends the result of a vector boolean value from a vector of i1 to a wider ty...
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action)
Indicate that the specified operation does not work with the specified type and indicate what to do a...
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
void setMinStackArgumentAlignment(Align Alignment)
Set the minimum stack alignment of an argument.
const TargetMachine & getTargetMachine() const
void setHasExtractBitsInsn(bool hasExtractInsn=true)
Tells the code generator that the target has BitExtract instructions.
MVT getRegisterType(LLVMContext &Context, EVT VT) const
Return the type of registers that this ValueType will eventually require.
virtual unsigned getNumRegisters(LLVMContext &Context, EVT VT, std::optional< MVT > RegisterVT=std::nullopt) const
Return the number of registers that this ValueType will eventually require.
void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits)
Set the maximum atomic operation size supported by the backend.
void setMinFunctionAlignment(Align Alignment)
Set the target's minimum function alignment.
void setBooleanContents(BooleanContent Ty)
Specify how the target extends the result of integer and floating point boolean values from i1 to a w...
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified truncating store does not work with the specified type and indicate what ...
void setStackPointerRegisterToSaveRestore(Register R)
If set to a physical register, this specifies the register that llvm.savestack/llvm....
void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT)
If Opc/OrigVT is specified as being promoted, the promotion code defaults to trying a larger integer/...
void setTargetDAGCombine(ArrayRef< ISD::NodeType > NTs)
Targets should invoke this method for each target independent node that they want to provide a custom...
virtual bool useSoftFloat() const
Align getMinStackArgumentAlignment() const
Return the minimum stack alignment of an argument.
void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified load with extension does not work with the specified type and indicate wh...
std::vector< ArgListEntry > ArgListTy
unsigned MaxStoresPerMemcpy
Specify maximum number of store instructions per memcpy call.
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
virtual SDValue LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, SelectionDAG &DAG) const
Lower TLS global address SDNode for target independent emulated TLS model.
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
bool isPositionIndependent() const
virtual ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const
Examine constraint string and operand type and determine a weight value.
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
TargetLowering(const TargetLowering &)=delete
virtual ArrayRef< MCPhysReg > getRoundingControlRegisters() const
Returns a 0 terminated array of rounding control registers that can be attached into strict FP call.
virtual void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const
Lower the specified operand into the Ops vector.
virtual unsigned getJumpTableEncoding() const
Return the entry encoding for a jump table in the current function.
virtual void LowerOperationWrapper(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const
This callback is invoked by the type legalizer to legalize nodes with an illegal operand type but leg...
void setTypeIdForCallsiteInfo(const CallBase *CB, MachineFunction &MF, MachineFunction::CallSiteInfo &CSInfo) const
TLSModel::Model getTLSModel(const GlobalValue *GV) const
Returns the TLS model which should be used for the given global variable.
bool useEmulatedTLS() const
Returns true if this target uses emulated TLS.
virtual TargetLoweringObjectFile * getObjFileLowering() const
TargetOptions Options
unsigned EnableFastISel
EnableFastISel - This flag enables fast-path instruction selection which trades away generated code q...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:43
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:837
@ STACKRESTORE
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain.
@ STACKSAVE
STACKSAVE - STACKSAVE has one operand, an input chain.
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:516
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:797
@ VAEND
VAEND, VASTART - VAEND and VASTART have three operands: an input chain, pointer, and a SRCVALUE.
@ ATOMIC_STORE
OUTCHAIN = ATOMIC_STORE(INCHAIN, val, ptr) This corresponds to "store atomic" instruction.
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:871
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:523
@ GlobalAddress
Definition ISDOpcodes.h:90
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ MEMBARRIER
MEMBARRIER - Compiler barrier only; generate a no-op.
@ ATOMIC_FENCE
OUTCHAIN = ATOMIC_FENCE(INCHAIN, ordering, scope) This corresponds to the fence instruction.
@ SDIVREM
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition ISDOpcodes.h:282
@ FP16_TO_FP
FP16_TO_FP, FP_TO_FP16 - These operators are used to perform promotions and truncation for half-preci...
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:256
@ GlobalTLSAddress
Definition ISDOpcodes.h:91
@ EH_RETURN
OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER) - This node represents 'eh_return' gcc dwarf builtin,...
Definition ISDOpcodes.h:158
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:862
@ TargetJumpTable
Definition ISDOpcodes.h:190
@ FSINCOS
FSINCOS - Compute both fsin and fcos as a single operation.
@ BR_CC
BR_CC - Conditional branch.
@ BR_JT
BR_JT - Jumptable branch.
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:546
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:553
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:814
@ ATOMIC_LOAD
Val, OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr) This corresponds to "load atomic" instruction.
@ VACOPY
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer,...
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:779
@ FMINNUM_IEEE
FMINNUM_IEEE/FMAXNUM_IEEE - Perform floating-point minimumNumber or maximumNumber on two values,...
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:868
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:829
@ FMINNUM
FMINNUM/FMAXNUM - Perform floating-point minimum maximum on two values, following IEEE-754 definition...
@ DYNAMIC_STACKALLOC
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary.
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:906
@ EH_DWARF_CFA
EH_DWARF_CFA - This node represents the pointer to the DWARF Canonical Frame Address (CFA),...
Definition ISDOpcodes.h:152
@ FRAMEADDR
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG.
Definition ISDOpcodes.h:112
@ STRICT_FP_TO_UINT
Definition ISDOpcodes.h:483
@ STRICT_FP_TO_SINT
STRICT_FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:482
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:944
@ READCYCLECOUNTER
READCYCLECOUNTER - This corresponds to the readcyclecounter intrinsic.
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:749
@ TRAP
TRAP - Trapping instruction.
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:874
@ VAARG
VAARG - VAARG has four operands: an input chain, a pointer, a SRCVALUE, and the alignment.
@ BRCOND
BRCOND - Conditional branch.
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:851
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:64
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:539
@ CALLSEQ_START
CALLSEQ_START/CALLSEQ_END - These operators mark the beginning and end of a call sequence,...
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, EVT Type)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
@ Bitcast
Perform the operation on a different, but equivalently sized type.
@ MO_TLSGD
On a symbol operand, this indicates that the immediate is the offset to the slot in GOT which stores ...
Flag
These should be considered private to the implementation of the MCInstrDesc class.
MCRegister matchRegisterName(StringRef Name, const MCRegisterInfo &MRI, unsigned RegClassID, unsigned AltIdx)
Match a symbolic name in RegClassID, or return an invalid register.
int getCPURegisterIndex(StringRef Name, const MCRegisterInfo &MRI, unsigned AltIdx, bool *IsDeprecated=nullptr)
Return a GPR name's hardware index, or -1 if unknown.
FastISel * createFastISel(FunctionLoweringInfo &funcInfo, const TargetLibraryInfo *libInfo, const LibcallLoweringInfo *libcallLowering)
Not(const Pred &P) -> Not< Pred >
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
Definition LLVMContext.h:55
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:58
initializer< Ty > init(const Ty &Val)
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
This is an optimization pass for GlobalISel generic memory operations.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
@ Offset
Definition DWP.cpp:577
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Dead
Unused definition.
@ Kill
The last use of a register.
@ Undef
Value of the register doesn't matter.
@ EarlyClobber
Register definition happens before uses.
@ Define
Register definition.
constexpr RegState getKillRegState(bool B)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool CCAssignFn(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
CCAssignFn - This function assigns a location for Val, updating State to reflect the change.
@ Store
The extracted value is stored (ExtractElement only).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
constexpr bool isShiftedMask_64(uint64_t Value)
Return true if the argument contains a non-empty sequence of ones with the remainder zero (64 bit ver...
Definition MathExtras.h:274
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
@ Other
Any other memory.
Definition ModRef.h:68
@ AfterLegalizeDAG
Definition DAGCombine.h:19
const MipsTargetLowering * createMips16TargetLowering(const MipsTargetMachine &TM, const MipsSubtarget &STI)
Create MipsTargetLowering objects.
@ Or
Bitwise or logical OR of integers.
@ Add
Sum of integers.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
const MipsTargetLowering * createMipsSETargetLowering(const MipsTargetMachine &TM, const MipsSubtarget &STI)
LLVM_ABI bool getAsUnsignedInteger(StringRef Str, unsigned Radix, unsigned long long &Result)
Helper functions for StringRef::getAsInteger.
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:78
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
Extended Value Type.
Definition ValueTypes.h:35
EVT changeVectorElementTypeToInteger() const
Return a vector with the same number of elements as this vector, but with the element type converted ...
Definition ValueTypes.h:90
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:323
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
bool isPow2VectorType() const
Returns true if the given vector is a power of 2.
Definition ValueTypes.h:501
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:339
static EVT getFloatingPointVT(unsigned BitWidth)
Returns the EVT that represents a floating-point type with the given number of bits.
Definition ValueTypes.h:55
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
bool isRound() const
Return true if the size is a power-of-two number of bytes.
Definition ValueTypes.h:271
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:351
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:359
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:160
Align getNonZeroOrigAlign() const
SmallVector< ArgRegPair, 1 > ArgRegPairs
Vector of call argument and its forwarding register.
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getGOT(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a GOT entry.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
This structure contains all information that is necessary for lowering calls.
SmallVector< ISD::InputArg, 32 > Ins
SmallVector< ISD::OutputArg, 32 > Outs