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)
1973 .addReg(OldValCopy)
1974 .addReg(NewValCopy)
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, bool IsPICCall,
3274 bool GlobalOrExternal, bool LocalLinkage, bool IsCallReloc,
3275 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
3276 // Insert node "GP copy globalreg" before call to function.
3277 //
3278 // R_MIPS_CALL* operators (emitted when non-local functions are called
3279 // in PIC mode) allow symbols to be resolved via lazy binding.
3280 // The lazy binding stub requires GP to point to the GOT.
3281 // Note that we don't need GP to point to the GOT for indirect calls
3282 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
3283 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
3284 // used for the function (that is, Mips linker doesn't generate lazy binding
3285 // stub for a function whose address is taken in the program).
3286 if (IsPICCall && !LocalLinkage && IsCallReloc) {
3287 unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
3288 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
3289 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
3290 }
3291
3292 // Build a sequence of copy-to-reg nodes chained together with token
3293 // chain and flag operands which copy the outgoing args into registers.
3294 // The InGlue in necessary since all emitted instructions must be
3295 // stuck together.
3296 SDValue InGlue;
3297
3298 for (auto &R : RegsToPass) {
3299 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, R.first, R.second, InGlue);
3300 InGlue = Chain.getValue(1);
3301 }
3302
3303 // Add argument registers to the end of the list so that they are
3304 // known live into the call.
3305 for (auto &R : RegsToPass)
3306 Ops.push_back(CLI.DAG.getRegister(R.first, R.second.getValueType()));
3307
3308 // Add a register mask operand representing the call-preserved registers.
3309 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3310 const uint32_t *Mask =
3311 TRI->getCallPreservedMask(CLI.DAG.getMachineFunction(), CLI.CallConv);
3312 assert(Mask && "Missing call preserved mask for calling convention");
3313 if (Subtarget.inMips16HardFloat()) {
3315 StringRef Sym = G->getGlobal()->getName();
3316 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3317 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
3319 }
3320 }
3321 }
3322 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
3323
3324 if (InGlue.getNode())
3325 Ops.push_back(InGlue);
3326}
3327
3329 SDNode *Node) const {
3330 switch (MI.getOpcode()) {
3331 default:
3332 return;
3333 case Mips::JALR:
3334 case Mips::JALRPseudo:
3335 case Mips::JALR64:
3336 case Mips::JALR64Pseudo:
3337 case Mips::JALR16_MM:
3338 case Mips::JALRC16_MMR6:
3339 case Mips::TAILCALLREG:
3340 case Mips::TAILCALLREG64:
3341 case Mips::TAILCALLR6REG:
3342 case Mips::TAILCALL64R6REG:
3343 case Mips::TAILCALLREG_MM:
3344 case Mips::TAILCALLREG_MMR6: {
3345 if (!EmitJalrReloc ||
3346 Subtarget.inMips16Mode() ||
3348 Node->getNumOperands() < 1 ||
3349 Node->getOperand(0).getNumOperands() < 2) {
3350 return;
3351 }
3352 // We are after the callee address, set by LowerCall().
3353 // If added to MI, asm printer will emit .reloc R_MIPS_JALR for the
3354 // symbol.
3355 const SDValue TargetAddr = Node->getOperand(0).getOperand(1);
3356 StringRef Sym;
3357 if (const GlobalAddressSDNode *G =
3359 // We must not emit the R_MIPS_JALR relocation against data symbols
3360 // since this will cause run-time crashes if the linker replaces the
3361 // call instruction with a relative branch to the data symbol.
3362 if (!isa<Function>(G->getGlobal())) {
3363 LLVM_DEBUG(dbgs() << "Not adding R_MIPS_JALR against data symbol "
3364 << G->getGlobal()->getName() << "\n");
3365 return;
3366 }
3367 Sym = G->getGlobal()->getName();
3368 }
3369 else if (const ExternalSymbolSDNode *ES =
3371 Sym = ES->getSymbol();
3372 }
3373
3374 if (Sym.empty())
3375 return;
3376
3377 MachineFunction *MF = MI.getParent()->getParent();
3378 MCSymbol *S = MF->getContext().getOrCreateSymbol(Sym);
3379 LLVM_DEBUG(dbgs() << "Adding R_MIPS_JALR against " << Sym << "\n");
3381 }
3382 }
3383}
3384
3385/// LowerCall - functions arguments are copied from virtual regs to
3386/// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
3387SDValue
3388MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3389 SmallVectorImpl<SDValue> &InVals) const {
3390 SelectionDAG &DAG = CLI.DAG;
3391 SDLoc DL = CLI.DL;
3393 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3395 SDValue Chain = CLI.Chain;
3396 SDValue Callee = CLI.Callee;
3397 bool &IsTailCall = CLI.IsTailCall;
3398 CallingConv::ID CallConv = CLI.CallConv;
3399 bool IsVarArg = CLI.IsVarArg;
3400 const CallBase *CB = CLI.CB;
3401
3403 MachineFrameInfo &MFI = MF.getFrameInfo();
3405 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
3406 bool IsPIC = isPositionIndependent();
3407
3408 // Analyze operands of the call, assigning locations to each operand.
3410 MipsCCState CCInfo(
3411 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
3413
3414 const ExternalSymbolSDNode *ES =
3416
3417 // There is one case where CALLSEQ_START..CALLSEQ_END can be nested, which
3418 // is during the lowering of a call with a byval argument which produces
3419 // a call to memcpy. For the O32 case, this causes the caller to allocate
3420 // stack space for the reserved argument area for the callee, then recursively
3421 // again for the memcpy call. In the NEWABI case, this doesn't occur as those
3422 // ABIs mandate that the callee allocates the reserved argument area. We do
3423 // still produce nested CALLSEQ_START..CALLSEQ_END with zero space though.
3424 //
3425 // If the callee has a byval argument and memcpy is used, we are mandated
3426 // to already have produced a reserved argument area for the callee for O32.
3427 // Therefore, the reserved argument area can be reused for both calls.
3428 //
3429 // Other cases of calling memcpy cannot have a chain with a CALLSEQ_START
3430 // present, as we have yet to hook that node onto the chain.
3431 //
3432 // Hence, the CALLSEQ_START and CALLSEQ_END nodes can be eliminated in this
3433 // case. GCC does a similar trick, in that wherever possible, it calculates
3434 // the maximum out going argument area (including the reserved area), and
3435 // preallocates the stack space on entrance to the caller.
3436 //
3437 // FIXME: We should do the same for efficiency and space.
3438
3439 // Note: The check on the calling convention below must match
3440 // MipsABIInfo::GetCalleeAllocdArgSizeInBytes().
3441 bool MemcpyInByVal = ES && StringRef(ES->getSymbol()) == "memcpy" &&
3442 CallConv != CallingConv::Fast &&
3443 Chain.getOpcode() == ISD::CALLSEQ_START;
3444
3445 // Allocate the reserved argument area. It seems strange to do this from the
3446 // caller side but removing it breaks the frame size calculation.
3447 unsigned ReservedArgArea =
3448 MemcpyInByVal ? 0 : ABI.GetCalleeAllocdArgSizeInBytes(CallConv);
3449 CCInfo.AllocateStack(ReservedArgArea, Align(1));
3450
3451 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
3452
3453 // Get a count of how many bytes are to be pushed on the stack.
3454 unsigned StackSize = CCInfo.getStackSize();
3455
3456 // Call site info for function parameters tracking and call base type info.
3458 // Set type id for call site info.
3459 setTypeIdForCallsiteInfo(CB, MF, CSInfo);
3460
3461 // Check if it's really possible to do a tail call.
3462 // For non-musttail calls, restrict to functions that won't require $gp
3463 // restoration. In PIC mode, calling external functions via tail call can
3464 // cause issues with $gp register handling (see D24763).
3465 bool IsMustTail = CLI.CB && CLI.CB->isMustTailCall();
3466 bool CalleeIsLocal = true;
3468 const GlobalValue *GV = G->getGlobal();
3469 bool HasLocalLinkage = GV->hasLocalLinkage() || GV->hasPrivateLinkage();
3470 bool HasHiddenVisibility =
3472 if (GV->isDeclarationForLinker())
3473 CalleeIsLocal = HasLocalLinkage || HasHiddenVisibility;
3474 else
3475 CalleeIsLocal = GV->isDSOLocal();
3476 }
3477
3478 if (IsTailCall) {
3479 if (!UseMipsTailCalls) {
3480 IsTailCall = false;
3481 if (IsMustTail)
3482 report_fatal_error("failed to perform tail call elimination on a call "
3483 "site marked musttail");
3484 } else {
3485 bool Eligible = isEligibleForTailCallOptimization(
3486 CCInfo, StackSize, *MF.getInfo<MipsFunctionInfo>());
3487 if (!Eligible || !CalleeIsLocal) {
3488 IsTailCall = false;
3489 if (IsMustTail)
3491 "failed to perform tail call elimination on a call "
3492 "site marked musttail");
3493 }
3494 }
3495 }
3496
3497 if (IsTailCall)
3498 ++NumTailCalls;
3499
3500 // Chain is the output chain of the last Load/Store or CopyToReg node.
3501 // ByValChain is the output chain of the last Memcpy node created for copying
3502 // byval arguments to the stack.
3503 unsigned StackAlignment = TFL->getStackAlignment();
3504 StackSize = alignTo(StackSize, StackAlignment);
3505
3506 if (!(IsTailCall || MemcpyInByVal))
3507 Chain = DAG.getCALLSEQ_START(Chain, StackSize, 0, DL);
3508
3509 SDValue StackPtr =
3510 DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP,
3512 std::deque<std::pair<unsigned, SDValue>> RegsToPass;
3513 SmallVector<SDValue, 8> MemOpChains;
3514
3515 CCInfo.rewindByValRegsInfo();
3516
3517 // Walk the register/memloc assignments, inserting copies/loads.
3518 for (unsigned i = 0, e = ArgLocs.size(), OutIdx = 0; i != e; ++i, ++OutIdx) {
3519 SDValue Arg = OutVals[OutIdx];
3520 CCValAssign &VA = ArgLocs[i];
3521 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
3522 ISD::ArgFlagsTy Flags = Outs[OutIdx].Flags;
3523 bool UseUpperBits = false;
3524
3525 // ByVal Arg.
3526 if (Flags.isByVal()) {
3527 unsigned FirstByValReg, LastByValReg;
3528 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3529 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3530
3531 assert(Flags.getByValSize() &&
3532 "ByVal args of size 0 should have been ignored by front-end.");
3533 assert(ByValIdx < CCInfo.getInRegsParamsCount());
3534 assert(!IsTailCall &&
3535 "Do not tail-call optimize if there is a byval argument.");
3536 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
3537 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
3538 VA);
3539 CCInfo.nextInRegsParam();
3540 continue;
3541 }
3542
3543 // Promote the value if needed.
3544 switch (VA.getLocInfo()) {
3545 default:
3546 llvm_unreachable("Unknown loc info!");
3547 case CCValAssign::Full:
3548 if (VA.isRegLoc()) {
3549 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
3550 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
3551 (ValVT == MVT::i64 && LocVT == MVT::f64))
3552 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3553 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
3554 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
3555 Arg, DAG.getConstant(0, DL, MVT::i32));
3556 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
3557 Arg, DAG.getConstant(1, DL, MVT::i32));
3558 if (!Subtarget.isLittle())
3559 std::swap(Lo, Hi);
3560
3561 assert(VA.needsCustom());
3562
3563 Register LocRegLo = VA.getLocReg();
3564 Register LocRegHigh = ArgLocs[++i].getLocReg();
3565 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
3566 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
3567 continue;
3568 }
3569 }
3570 break;
3571 case CCValAssign::BCvt:
3572 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3573 break;
3575 UseUpperBits = true;
3576 [[fallthrough]];
3577 case CCValAssign::SExt:
3578 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
3579 break;
3581 UseUpperBits = true;
3582 [[fallthrough]];
3583 case CCValAssign::ZExt:
3584 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
3585 break;
3587 UseUpperBits = true;
3588 [[fallthrough]];
3589 case CCValAssign::AExt:
3590 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
3591 break;
3592 }
3593
3594 if (UseUpperBits) {
3595 unsigned ValSizeInBits = Outs[OutIdx].ArgVT.getSizeInBits();
3596 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3597 Arg = DAG.getNode(
3598 ISD::SHL, DL, VA.getLocVT(), Arg,
3599 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3600 }
3601
3602 // Arguments that can be passed on register must be kept at
3603 // RegsToPass vector
3604 if (VA.isRegLoc()) {
3605 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3606
3607 // If the parameter is passed through reg $D, which splits into
3608 // two physical registers, avoid creating call site info.
3609 if (Mips::AFGR64RegClass.contains(VA.getLocReg()))
3610 continue;
3611
3612 // Collect CSInfo about which register passes which parameter.
3613 const TargetOptions &Options = DAG.getTarget().Options;
3614 if (Options.EmitCallSiteInfo)
3615 CSInfo.ArgRegPairs.emplace_back(VA.getLocReg(), i);
3616
3617 continue;
3618 }
3619
3620 // Register can't get to this point...
3621 assert(VA.isMemLoc());
3622
3623 // emit ISD::STORE whichs stores the
3624 // parameter value to a stack Location
3625 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
3626 Chain, Arg, DL, IsTailCall, DAG));
3627 }
3628
3629 // Transform all store nodes into one single node because all store
3630 // nodes are independent of each other.
3631 if (!MemOpChains.empty())
3632 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3633
3634 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3635 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3636 // node so that legalize doesn't hack it.
3637
3638 EVT Ty = Callee.getValueType();
3639 bool GlobalOrExternal = false, IsCallReloc = false;
3640
3641 // The long-calls feature is ignored in case of PIC.
3642 // While we do not support -mshared / -mno-shared properly,
3643 // ignore long-calls in case of -mabicalls too.
3644 if (!Subtarget.isABICalls() && !IsPIC) {
3645 // If the function should be called using "long call",
3646 // get its address into a register to prevent using
3647 // of the `jal` instruction for the direct call.
3648 if (auto *N = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3649 if (Subtarget.useLongCalls())
3650 Callee = Subtarget.hasSym32()
3651 ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
3652 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
3653 } else if (auto *N = dyn_cast<GlobalAddressSDNode>(Callee)) {
3654 bool UseLongCalls = Subtarget.useLongCalls();
3655 // If the function has long-call/far/near attribute
3656 // it overrides command line switch pased to the backend.
3657 if (auto *F = dyn_cast<Function>(N->getGlobal())) {
3658 if (F->hasFnAttribute("long-call"))
3659 UseLongCalls = true;
3660 else if (F->hasFnAttribute("short-call"))
3661 UseLongCalls = false;
3662 }
3663 if (UseLongCalls)
3664 Callee = Subtarget.hasSym32()
3665 ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
3666 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
3667 }
3668 }
3669
3670 bool LocalLinkage = false;
3671 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3672 if (Subtarget.isTargetCOFF() &&
3673 G->getGlobal()->hasDLLImportStorageClass()) {
3674 assert(Subtarget.isTargetWindows() &&
3675 "Windows is the only supported COFF target");
3676 auto PtrInfo = MachinePointerInfo();
3677 Callee = DAG.getLoad(Ty, DL, Chain,
3678 getDllimportSymbol(G, SDLoc(G), Ty, DAG), PtrInfo);
3679 } else if (IsPIC) {
3680 const GlobalValue *Val = G->getGlobal();
3681 LocalLinkage = Val->hasLocalLinkage();
3682
3683 if (LocalLinkage)
3684 Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
3685 else if (Subtarget.useXGOT()) {
3687 MipsII::MO_CALL_LO16, Chain,
3688 FuncInfo->callPtrInfo(MF, Val));
3689 IsCallReloc = true;
3690 } else {
3691 Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3692 FuncInfo->callPtrInfo(MF, Val));
3693 IsCallReloc = true;
3694 }
3695 } else
3696 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL,
3697 getPointerTy(DAG.getDataLayout()), 0,
3699 GlobalOrExternal = true;
3700 }
3701 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3702 const char *Sym = S->getSymbol();
3703
3704 if (!IsPIC) // static
3707 else if (Subtarget.useXGOT()) {
3709 MipsII::MO_CALL_LO16, Chain,
3710 FuncInfo->callPtrInfo(MF, Sym));
3711 IsCallReloc = true;
3712 } else { // PIC
3713 Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3714 FuncInfo->callPtrInfo(MF, Sym));
3715 IsCallReloc = true;
3716 }
3717
3718 GlobalOrExternal = true;
3719 }
3720
3721 SmallVector<SDValue, 8> Ops(1, Chain);
3722 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3723
3724 getOpndList(Ops, RegsToPass, IsPIC, GlobalOrExternal, LocalLinkage,
3725 IsCallReloc, CLI, Callee, Chain);
3726
3727 if (IsTailCall) {
3729 SDValue Ret = DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
3730 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
3731 return Ret;
3732 }
3733
3734 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
3735 SDValue InGlue = Chain.getValue(1);
3736
3737 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
3738
3739 // Create the CALLSEQ_END node in the case of where it is not a call to
3740 // memcpy.
3741 if (!(MemcpyInByVal)) {
3742 Chain = DAG.getCALLSEQ_END(Chain, StackSize, 0, InGlue, DL);
3743 InGlue = Chain.getValue(1);
3744 }
3745
3746 // Handle result values, copying them out of physregs into vregs that we
3747 // return.
3748 return LowerCallResult(Chain, InGlue, CallConv, IsVarArg, Ins, DL, DAG,
3749 InVals, CLI);
3750}
3751
3752/// LowerCallResult - Lower the result values of a call into the
3753/// appropriate copies out of appropriate physical registers.
3754SDValue MipsTargetLowering::LowerCallResult(
3755 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool IsVarArg,
3756 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3759 // Assign locations to each value returned by this call.
3761 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
3762 *DAG.getContext());
3763
3764 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
3765
3766 // Copy all of the result registers out of their specified physreg.
3767 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3768 CCValAssign &VA = RVLocs[i];
3769 assert(VA.isRegLoc() && "Can only return in registers!");
3770
3771 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
3772 RVLocs[i].getLocVT(), InGlue);
3773 Chain = Val.getValue(1);
3774 InGlue = Val.getValue(2);
3775
3776 if (VA.isUpperBitsInLoc()) {
3777 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
3778 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3779 unsigned Shift =
3781 Val = DAG.getNode(
3782 Shift, DL, VA.getLocVT(), Val,
3783 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3784 }
3785
3786 switch (VA.getLocInfo()) {
3787 default:
3788 llvm_unreachable("Unknown loc info!");
3789 case CCValAssign::Full:
3790 break;
3791 case CCValAssign::BCvt:
3792 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3793 break;
3794 case CCValAssign::AExt:
3796 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3797 break;
3798 case CCValAssign::ZExt:
3800 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
3801 DAG.getValueType(VA.getValVT()));
3802 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3803 break;
3804 case CCValAssign::SExt:
3806 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
3807 DAG.getValueType(VA.getValVT()));
3808 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3809 break;
3810 }
3811
3812 InVals.push_back(Val);
3813 }
3814
3815 return Chain;
3816}
3817
3819 EVT ArgVT, const SDLoc &DL,
3820 SelectionDAG &DAG) {
3821 MVT LocVT = VA.getLocVT();
3822 EVT ValVT = VA.getValVT();
3823
3824 // Shift into the upper bits if necessary.
3825 switch (VA.getLocInfo()) {
3826 default:
3827 break;
3831 unsigned ValSizeInBits = ArgVT.getSizeInBits();
3832 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3833 unsigned Opcode =
3835 Val = DAG.getNode(
3836 Opcode, DL, VA.getLocVT(), Val,
3837 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3838 break;
3839 }
3840 }
3841
3842 // If this is an value smaller than the argument slot size (32-bit for O32,
3843 // 64-bit for N32/N64), it has been promoted in some way to the argument slot
3844 // size. Extract the value and insert any appropriate assertions regarding
3845 // sign/zero extension.
3846 switch (VA.getLocInfo()) {
3847 default:
3848 llvm_unreachable("Unknown loc info!");
3849 case CCValAssign::Full:
3850 break;
3852 case CCValAssign::AExt:
3853 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3854 break;
3856 case CCValAssign::SExt:
3857 Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
3858 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3859 break;
3861 case CCValAssign::ZExt:
3862 Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
3863 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3864 break;
3865 case CCValAssign::BCvt:
3866 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
3867 break;
3868 }
3869
3870 return Val;
3871}
3872
3873//===----------------------------------------------------------------------===//
3874// Formal Arguments Calling Convention Implementation
3875//===----------------------------------------------------------------------===//
3876/// LowerFormalArguments - transform physical registers into virtual registers
3877/// and generate load operations for arguments places on the stack.
3878SDValue MipsTargetLowering::LowerFormalArguments(
3879 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
3880 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3881 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3883 MachineFrameInfo &MFI = MF.getFrameInfo();
3884 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3885
3886 MipsFI->setVarArgsFrameIndex(0);
3887
3888 // Used with vargs to acumulate store chains.
3889 std::vector<SDValue> OutChains;
3890
3891 // Assign locations to all of the incoming arguments.
3893 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3894 *DAG.getContext());
3895 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), Align(1));
3897 Function::const_arg_iterator FuncArg = Func.arg_begin();
3898
3899 if (Func.hasFnAttribute("interrupt") && !Func.arg_empty())
3901 "Functions with the interrupt attribute cannot have arguments!");
3902
3903 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
3904 MipsFI->setFormalArgInfo(CCInfo.getStackSize(),
3905 CCInfo.getInRegsParamsCount() > 0);
3906
3907 unsigned CurArgIdx = 0;
3908 CCInfo.rewindByValRegsInfo();
3909
3910 for (unsigned i = 0, e = ArgLocs.size(), InsIdx = 0; i != e; ++i, ++InsIdx) {
3911 CCValAssign &VA = ArgLocs[i];
3912 if (Ins[InsIdx].isOrigArg()) {
3913 std::advance(FuncArg, Ins[InsIdx].getOrigArgIndex() - CurArgIdx);
3914 CurArgIdx = Ins[InsIdx].getOrigArgIndex();
3915 }
3916 EVT ValVT = VA.getValVT();
3917 ISD::ArgFlagsTy Flags = Ins[InsIdx].Flags;
3918 bool IsRegLoc = VA.isRegLoc();
3919
3920 if (Flags.isByVal()) {
3921 assert(Ins[InsIdx].isOrigArg() && "Byval arguments cannot be implicit");
3922 unsigned FirstByValReg, LastByValReg;
3923 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3924 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3925
3926 assert(Flags.getByValSize() &&
3927 "ByVal args of size 0 should have been ignored by front-end.");
3928 assert(ByValIdx < CCInfo.getInRegsParamsCount());
3929 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
3930 FirstByValReg, LastByValReg, VA, CCInfo);
3931 CCInfo.nextInRegsParam();
3932 continue;
3933 }
3934
3935 // Arguments stored on registers
3936 if (IsRegLoc) {
3937 MVT RegVT = VA.getLocVT();
3938 Register ArgReg = VA.getLocReg();
3939 const TargetRegisterClass *RC = getRegClassFor(RegVT);
3940
3941 // Transform the arguments stored on
3942 // physical registers into virtual ones
3943 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3944 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3945
3946 ArgValue =
3947 UnpackFromArgumentSlot(ArgValue, VA, Ins[InsIdx].ArgVT, DL, DAG);
3948
3949 // Handle floating point arguments passed in integer registers and
3950 // long double arguments passed in floating point registers.
3951 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3952 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
3953 (RegVT == MVT::f64 && ValVT == MVT::i64))
3954 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
3955 else if (ABI.IsO32() && RegVT == MVT::i32 &&
3956 ValVT == MVT::f64) {
3957 assert(VA.needsCustom() && "Expected custom argument for f64 split");
3958 CCValAssign &NextVA = ArgLocs[++i];
3959 unsigned Reg2 =
3960 addLiveIn(DAG.getMachineFunction(), NextVA.getLocReg(), RC);
3961 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
3962 if (!Subtarget.isLittle())
3963 std::swap(ArgValue, ArgValue2);
3964 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
3965 ArgValue, ArgValue2);
3966 }
3967
3968 InVals.push_back(ArgValue);
3969 } else { // VA.isRegLoc()
3970 MVT LocVT = VA.getLocVT();
3971
3972 assert(!VA.needsCustom() && "unexpected custom memory argument");
3973
3974 // Only arguments pased on the stack should make it here.
3975 assert(VA.isMemLoc());
3976
3977 // The stack pointer offset is relative to the caller stack frame.
3978 int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
3979 VA.getLocMemOffset(), true);
3980
3981 // Create load nodes to retrieve arguments from the stack
3982 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3983 SDValue ArgValue = DAG.getLoad(
3984 LocVT, DL, Chain, FIN,
3986 OutChains.push_back(ArgValue.getValue(1));
3987
3988 ArgValue =
3989 UnpackFromArgumentSlot(ArgValue, VA, Ins[InsIdx].ArgVT, DL, DAG);
3990
3991 InVals.push_back(ArgValue);
3992 }
3993 }
3994
3995 for (unsigned i = 0, e = ArgLocs.size(), InsIdx = 0; i != e; ++i, ++InsIdx) {
3996
3997 if (ArgLocs[i].needsCustom()) {
3998 ++i;
3999 continue;
4000 }
4001
4002 // The mips ABIs for returning structs by value requires that we copy
4003 // the sret argument into $v0 for the return. Save the argument into
4004 // a virtual register so that we can access it from the return points.
4005 if (Ins[InsIdx].Flags.isSRet()) {
4006 unsigned Reg = MipsFI->getSRetReturnReg();
4007 if (!Reg) {
4009 getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32));
4010 MipsFI->setSRetReturnReg(Reg);
4011 }
4012 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
4013 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
4014 break;
4015 }
4016 }
4017
4018 if (IsVarArg)
4019 writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
4020
4021 // All stores are grouped in one node to allow the matching between
4022 // the size of Ins and InVals. This only happens when on varg functions
4023 if (!OutChains.empty()) {
4024 OutChains.push_back(Chain);
4025 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
4026 }
4027
4028 return Chain;
4029}
4030
4031//===----------------------------------------------------------------------===//
4032// Return Value Calling Convention Implementation
4033//===----------------------------------------------------------------------===//
4034
4035bool
4036MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4037 MachineFunction &MF, bool IsVarArg,
4039 LLVMContext &Context, const Type *RetTy) const {
4041 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
4042 return CCInfo.CheckReturn(Outs, RetCC_Mips);
4043}
4044
4045bool MipsTargetLowering::shouldSignExtendTypeInLibCall(Type *Ty,
4046 bool IsSigned) const {
4047 if ((ABI.IsN32() || ABI.IsN64()) && Ty->isIntegerTy(32))
4048 return true;
4049
4050 return IsSigned;
4051}
4052
4053SDValue
4054MipsTargetLowering::LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
4055 const SDLoc &DL,
4056 SelectionDAG &DAG) const {
4058 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4059
4060 MipsFI->setISR();
4061
4062 return DAG.getNode(MipsISD::ERet, DL, MVT::Other, RetOps);
4063}
4064
4065SDValue
4066MipsTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
4067 bool IsVarArg,
4069 const SmallVectorImpl<SDValue> &OutVals,
4070 const SDLoc &DL, SelectionDAG &DAG) const {
4071 // CCValAssign - represent the assignment of
4072 // the return value to a location
4075
4076 // CCState - Info about the registers and stack slot.
4077 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
4078
4079 // Analyze return values.
4080 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
4081
4082 SDValue Glue;
4083 SmallVector<SDValue, 4> RetOps(1, Chain);
4084
4085 // Copy the result values into the output registers.
4086 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4087 SDValue Val = OutVals[i];
4088 CCValAssign &VA = RVLocs[i];
4089 assert(VA.isRegLoc() && "Can only return in registers!");
4090 bool UseUpperBits = false;
4091
4092 switch (VA.getLocInfo()) {
4093 default:
4094 llvm_unreachable("Unknown loc info!");
4095 case CCValAssign::Full:
4096 break;
4097 case CCValAssign::BCvt:
4098 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
4099 break;
4101 UseUpperBits = true;
4102 [[fallthrough]];
4103 case CCValAssign::AExt:
4104 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
4105 break;
4107 UseUpperBits = true;
4108 [[fallthrough]];
4109 case CCValAssign::ZExt:
4110 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
4111 break;
4113 UseUpperBits = true;
4114 [[fallthrough]];
4115 case CCValAssign::SExt:
4116 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
4117 break;
4118 }
4119
4120 if (UseUpperBits) {
4121 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
4122 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
4123 Val = DAG.getNode(
4124 ISD::SHL, DL, VA.getLocVT(), Val,
4125 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
4126 }
4127
4128 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
4129
4130 // Guarantee that all emitted copies are stuck together with flags.
4131 Glue = Chain.getValue(1);
4132 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4133 }
4134
4135 // The mips ABIs for returning structs by value requires that we copy
4136 // the sret argument into $v0 for the return. We saved the argument into
4137 // a virtual register in the entry block, so now we copy the value out
4138 // and into $v0.
4139 if (MF.getFunction().hasStructRetAttr()) {
4140 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4141 unsigned Reg = MipsFI->getSRetReturnReg();
4142
4143 if (!Reg)
4144 llvm_unreachable("sret virtual register not created in the entry block");
4145 SDValue Val =
4146 DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
4147 unsigned V0 = ABI.getReturnRegPtr(0);
4148
4149 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Glue);
4150 Glue = Chain.getValue(1);
4151 RetOps.push_back(DAG.getRegister(V0, getPointerTy(DAG.getDataLayout())));
4152 }
4153
4154 RetOps[0] = Chain; // Update chain.
4155
4156 // Add the glue if we have it.
4157 if (Glue.getNode())
4158 RetOps.push_back(Glue);
4159
4160 // ISRs must use "eret".
4161 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt"))
4162 return LowerInterruptReturn(RetOps, DL, DAG);
4163
4164 // Standard return on Mips is a "jr $ra"
4165 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
4166}
4167
4168//===----------------------------------------------------------------------===//
4169// Mips Inline Assembly Support
4170//===----------------------------------------------------------------------===//
4171
4172/// getConstraintType - Given a constraint letter, return the type of
4173/// constraint it is for this target.
4175MipsTargetLowering::getConstraintType(StringRef Constraint) const {
4176 // Mips specific constraints
4177 // GCC config/mips/constraints.md
4178 //
4179 // 'd' : An address register. Equivalent to r
4180 // unless generating MIPS16 code.
4181 // 'y' : Equivalent to r; retained for
4182 // backwards compatibility.
4183 // 'c' : A register suitable for use in an indirect
4184 // jump. This will always be $25 for -mabicalls.
4185 // 'l' : The lo register. 1 word storage.
4186 // 'x' : The hilo register pair. Double word storage.
4187 if (Constraint.size() == 1) {
4188 switch (Constraint[0]) {
4189 default : break;
4190 case 'd':
4191 case 'y':
4192 case 'f':
4193 case 'c':
4194 case 'l':
4195 case 'x':
4196 return C_RegisterClass;
4197 case 'R':
4198 return C_Memory;
4199 }
4200 }
4201
4202 if (Constraint == "ZC")
4203 return C_Memory;
4204
4205 return TargetLowering::getConstraintType(Constraint);
4206}
4207
4208/// Examine constraint type and operand type and determine a weight value.
4209/// This object must already have been set up with the operand type
4210/// and the current alternative constraint selected.
4212MipsTargetLowering::getSingleConstraintMatchWeight(
4213 AsmOperandInfo &info, const char *constraint) const {
4215 Value *CallOperandVal = info.CallOperandVal;
4216 // If we don't have a value, we can't do a match,
4217 // but allow it at the lowest weight.
4218 if (!CallOperandVal)
4219 return CW_Default;
4220 Type *type = CallOperandVal->getType();
4221 // Look at the constraint type.
4222 switch (*constraint) {
4223 default:
4225 break;
4226 case 'd':
4227 case 'y':
4228 if (type->isIntegerTy())
4229 weight = CW_Register;
4230 break;
4231 case 'f': // FPU or MSA register
4232 if (Subtarget.hasMSA() && type->isVectorTy() &&
4233 type->getPrimitiveSizeInBits().getFixedValue() == 128)
4234 weight = CW_Register;
4235 else if (type->isFloatTy())
4236 weight = CW_Register;
4237 break;
4238 case 'c': // $25 for indirect jumps
4239 case 'l': // lo register
4240 case 'x': // hilo register pair
4241 if (type->isIntegerTy())
4242 weight = CW_SpecificReg;
4243 break;
4244 case 'I': // signed 16 bit immediate
4245 case 'J': // integer zero
4246 case 'K': // unsigned 16 bit immediate
4247 case 'L': // signed 32 bit immediate where lower 16 bits are 0
4248 case 'N': // immediate in the range of -65535 to -1 (inclusive)
4249 case 'O': // signed 15 bit immediate (+- 16383)
4250 case 'P': // immediate in the range of 65535 to 1 (inclusive)
4251 if (isa<ConstantInt>(CallOperandVal))
4252 weight = CW_Constant;
4253 break;
4254 case 'R':
4255 weight = CW_Memory;
4256 break;
4257 }
4258 return weight;
4259}
4260
4261/// This is a helper function to parse a physical register string and split it
4262/// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
4263/// that is returned indicates whether parsing was successful. The second flag
4264/// is true if the numeric part exists.
4265static std::pair<bool, bool> parsePhysicalReg(StringRef C, StringRef &Prefix,
4266 unsigned long long &Reg) {
4267 if (C.front() != '{' || C.back() != '}')
4268 return std::make_pair(false, false);
4269
4270 // Search for the first numeric character.
4271 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
4272 I = std::find_if(B, E, isdigit);
4273
4274 Prefix = StringRef(B, I - B);
4275
4276 // The second flag is set to false if no numeric characters were found.
4277 if (I == E)
4278 return std::make_pair(true, false);
4279
4280 // Parse the numeric characters.
4281 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
4282 true);
4283}
4284
4286 ISD::NodeType) const {
4287 bool Cond = !Subtarget.isABI_O32() && VT.getSizeInBits() == 32;
4288 EVT MinVT = getRegisterType(Context, Cond ? MVT::i64 : MVT::i32);
4289 return VT.bitsLT(MinVT) ? MinVT : VT;
4290}
4291
4292std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
4293parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
4294 const TargetRegisterInfo *TRI =
4296 const TargetRegisterClass *RC;
4297 StringRef Prefix;
4298 unsigned long long Reg;
4299
4300 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
4301
4302 if (!R.first)
4303 return std::make_pair(0U, nullptr);
4304
4305 for (unsigned RegClassID : {Mips::HI32RegClassID, Mips::LO32RegClassID}) {
4307 Prefix, *TRI, RegClassID, Mips::RegAliasName)) {
4308 // No numeric characters follow a hi/lo register name.
4309 if (R.second)
4310 return std::make_pair(0U, nullptr);
4311 return std::make_pair(NamedReg.id(), TRI->getRegClass(RegClassID));
4312 }
4313 }
4314
4315 if (Prefix.starts_with("$msa")) {
4316 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
4317
4318 // No numeric characters follow the name.
4319 if (R.second)
4320 return std::make_pair(0U, nullptr);
4321
4322 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
4324 Prefix.drop_front(), *TRI, Mips::MSACtrlRegClassID, Mips::RegAliasName);
4325 if (!Reg)
4326 return std::make_pair(0U, nullptr);
4327
4328 return std::make_pair(Reg, RC);
4329 }
4330
4331 if (!R.second)
4332 return std::make_pair(0U, nullptr);
4333
4334 if (Prefix == "$f") { // Parse $f0-$f31.
4335 // If the targets is single float only, always select 32-bit registers,
4336 // otherwise if the size of FP registers is 64-bit or Reg is an even number,
4337 // select the 64-bit register class. Otherwise, select the 32-bit register
4338 // class.
4339 if (VT == MVT::Other) {
4340 if (Subtarget.isSingleFloat())
4341 VT = MVT::f32;
4342 else
4343 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
4344 }
4345
4346 RC = getRegClassFor(VT);
4347
4348 if (RC == &Mips::AFGR64RegClass) {
4349 assert(Reg % 2 == 0);
4350 Reg >>= 1;
4351 }
4352 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
4353 RC = TRI->getRegClass(Mips::FCCRegClassID);
4354 else if (Prefix == "$w") { // Parse $w0-$w31.
4355 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
4356 } else { // Parse $0-$31.
4357 assert(Prefix == "$");
4358 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
4359 }
4360
4361 assert(Reg < RC->getNumRegs());
4362 return std::make_pair(*(RC->begin() + Reg), RC);
4363}
4364
4365/// Given a register class constraint, like 'r', if this corresponds directly
4366/// to an LLVM register class, return a register of 0 and the register class
4367/// pointer.
4368std::pair<unsigned, const TargetRegisterClass *>
4369MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
4370 StringRef Constraint,
4371 MVT VT) const {
4372 if (Constraint.size() == 1) {
4373 switch (Constraint[0]) {
4374 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
4375 case 'y': // Same as 'r'. Exists for compatibility.
4376 case 'r':
4377 if ((VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8 ||
4378 VT == MVT::i1) ||
4379 (VT == MVT::f32 && Subtarget.useSoftFloat())) {
4380 if (Subtarget.inMips16Mode())
4381 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
4382 return std::make_pair(0U, &Mips::GPR32RegClass);
4383 }
4384 if ((VT == MVT::i64 || (VT == MVT::f64 && Subtarget.useSoftFloat()) ||
4385 (VT == MVT::f64 && Subtarget.isSingleFloat())) &&
4386 !Subtarget.isGP64bit())
4387 return std::make_pair(0U, &Mips::GPR32RegClass);
4388 if ((VT == MVT::i64 || (VT == MVT::f64 && Subtarget.useSoftFloat()) ||
4389 (VT == MVT::f64 && Subtarget.isSingleFloat())) &&
4390 Subtarget.isGP64bit())
4391 return std::make_pair(0U, &Mips::GPR64RegClass);
4392 // This will generate an error message
4393 return std::make_pair(0U, nullptr);
4394 case 'f': // FPU or MSA register
4395 if (VT == MVT::v16i8)
4396 return std::make_pair(0U, &Mips::MSA128BRegClass);
4397 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
4398 return std::make_pair(0U, &Mips::MSA128HRegClass);
4399 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
4400 return std::make_pair(0U, &Mips::MSA128WRegClass);
4401 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
4402 return std::make_pair(0U, &Mips::MSA128DRegClass);
4403 else if (VT == MVT::f32)
4404 return std::make_pair(0U, &Mips::FGR32RegClass);
4405 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
4406 if (Subtarget.isFP64bit())
4407 return std::make_pair(0U, &Mips::FGR64RegClass);
4408 return std::make_pair(0U, &Mips::AFGR64RegClass);
4409 }
4410 break;
4411 case 'c': // register suitable for indirect jump
4412 if (VT == MVT::i32)
4413 return std::make_pair(ABI.getTempReg(9, false).id(),
4414 &Mips::GPR32RegClass);
4415 if (VT == MVT::i64)
4416 return std::make_pair(ABI.getTempReg(9, true).id(),
4417 &Mips::GPR64RegClass);
4418 // This will generate an error message
4419 return std::make_pair(0U, nullptr);
4420 case 'l': // use the `lo` register to store values
4421 // that are no bigger than a word
4422 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8)
4423 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
4424 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
4425 case 'x': // use the concatenated `hi` and `lo` registers
4426 // to store doubleword values
4427 // Fixme: Not triggering the use of both hi and low
4428 // This will generate an error message
4429 return std::make_pair(0U, nullptr);
4430 }
4431 }
4432
4433 if (!Constraint.empty()) {
4434 std::pair<unsigned, const TargetRegisterClass *> R;
4435 R = parseRegForInlineAsmConstraint(Constraint, VT);
4436
4437 if (R.second)
4438 return R;
4439 }
4440
4441 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4442}
4443
4444/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4445/// vector. If it is invalid, don't add anything to Ops.
4446void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
4447 StringRef Constraint,
4448 std::vector<SDValue> &Ops,
4449 SelectionDAG &DAG) const {
4450 SDLoc DL(Op);
4451 SDValue Result;
4452
4453 // Only support length 1 constraints for now.
4454 if (Constraint.size() > 1)
4455 return;
4456
4457 char ConstraintLetter = Constraint[0];
4458 switch (ConstraintLetter) {
4459 default: break; // This will fall through to the generic implementation
4460 case 'I': // Signed 16 bit constant
4461 // If this fails, the parent routine will give an error
4462 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4463 EVT Type = Op.getValueType();
4464 int64_t Val = C->getSExtValue();
4465 if (isInt<16>(Val)) {
4467 break;
4468 }
4469 }
4470 return;
4471 case 'J': // integer zero
4472 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4473 EVT Type = Op.getValueType();
4474 int64_t Val = C->getZExtValue();
4475 if (Val == 0) {
4476 Result = DAG.getTargetConstant(0, DL, Type);
4477 break;
4478 }
4479 }
4480 return;
4481 case 'K': // unsigned 16 bit immediate
4482 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4483 EVT Type = Op.getValueType();
4484 uint64_t Val = C->getZExtValue();
4485 if (isUInt<16>(Val)) {
4486 Result = DAG.getTargetConstant(Val, DL, Type);
4487 break;
4488 }
4489 }
4490 return;
4491 case 'L': // signed 32 bit immediate where lower 16 bits are 0
4492 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4493 EVT Type = Op.getValueType();
4494 int64_t Val = C->getSExtValue();
4495 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
4497 break;
4498 }
4499 }
4500 return;
4501 case 'N': // immediate in the range of -65535 to -1 (inclusive)
4502 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4503 EVT Type = Op.getValueType();
4504 int64_t Val = C->getSExtValue();
4505 if ((Val >= -65535) && (Val <= -1)) {
4507 break;
4508 }
4509 }
4510 return;
4511 case 'O': // signed 15 bit immediate
4512 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4513 EVT Type = Op.getValueType();
4514 int64_t Val = C->getSExtValue();
4515 if ((isInt<15>(Val))) {
4517 break;
4518 }
4519 }
4520 return;
4521 case 'P': // immediate in the range of 1 to 65535 (inclusive)
4522 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4523 EVT Type = Op.getValueType();
4524 int64_t Val = C->getSExtValue();
4525 if ((Val <= 65535) && (Val >= 1)) {
4526 Result = DAG.getTargetConstant(Val, DL, Type);
4527 break;
4528 }
4529 }
4530 return;
4531 }
4532
4533 if (Result.getNode()) {
4534 Ops.push_back(Result);
4535 return;
4536 }
4537
4539}
4540
4541bool MipsTargetLowering::isLegalAddressingMode(const DataLayout &DL,
4542 const AddrMode &AM, Type *Ty,
4543 unsigned AS,
4544 Instruction *I) const {
4545 // No global is ever allowed as a base.
4546 if (AM.BaseGV)
4547 return false;
4548
4549 switch (AM.Scale) {
4550 case 0: // "r+i" or just "i", depending on HasBaseReg.
4551 break;
4552 case 1:
4553 if (!AM.HasBaseReg) // allow "r+i".
4554 break;
4555 return false; // disallow "r+r" or "r+r+i".
4556 default:
4557 return false;
4558 }
4559
4560 return true;
4561}
4562
4563bool
4564MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4565 // The Mips target isn't yet aware of offsets.
4566 return false;
4567}
4568
4569EVT MipsTargetLowering::getOptimalMemOpType(
4570 LLVMContext &Context, const MemOp &Op,
4571 const AttributeList &FuncAttributes) const {
4572 if (Subtarget.hasMips64())
4573 return MVT::i64;
4574
4575 return MVT::i32;
4576}
4577
4578bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
4579 bool ForCodeSize) const {
4580 if (VT != MVT::f32 && VT != MVT::f64)
4581 return false;
4582 if (Imm.isNegZero())
4583 return false;
4584 return Imm.isZero();
4585}
4586
4587bool MipsTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
4588 return isInt<16>(Imm);
4589}
4590
4591bool MipsTargetLowering::isLegalAddImmediate(int64_t Imm) const {
4592 return isInt<16>(Imm);
4593}
4594
4596 if (!isPositionIndependent())
4598 if (ABI.IsN64())
4601}
4602
4603SDValue MipsTargetLowering::getPICJumpTableRelocBase(SDValue Table,
4604 SelectionDAG &DAG) const {
4605 if (!isPositionIndependent())
4606 return Table;
4608}
4609
4611 return Subtarget.useSoftFloat();
4612}
4613
4614void MipsTargetLowering::copyByValRegs(
4615 SDValue Chain, const SDLoc &DL, std::vector<SDValue> &OutChains,
4616 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
4617 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
4618 unsigned FirstReg, unsigned LastReg, const CCValAssign &VA,
4619 MipsCCState &State) const {
4621 MachineFrameInfo &MFI = MF.getFrameInfo();
4622 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
4623 unsigned NumRegs = LastReg - FirstReg;
4624 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
4625 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
4626 int FrameObjOffset;
4627 ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
4628
4629 if (RegAreaSize)
4630 FrameObjOffset =
4631 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
4632 (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
4633 else
4634 FrameObjOffset = VA.getLocMemOffset();
4635
4636 // Create frame object.
4637 EVT PtrTy = getPointerTy(DAG.getDataLayout());
4638 // Make the fixed object stored to mutable so that the load instructions
4639 // referencing it have their memory dependencies added.
4640 // Set the frame object as isAliased which clears the underlying objects
4641 // vector in ScheduleDAGInstrs::buildSchedGraph() resulting in addition of all
4642 // stores as dependencies for loads referencing this fixed object.
4643 int FI = MFI.CreateFixedObject(FrameObjSize, FrameObjOffset, false, true);
4644 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4645 InVals.push_back(FIN);
4646
4647 if (!NumRegs)
4648 return;
4649
4650 // Copy arg registers.
4651 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
4652 const TargetRegisterClass *RC = getRegClassFor(RegTy);
4653
4654 for (unsigned I = 0; I < NumRegs; ++I) {
4655 unsigned ArgReg = ByValArgRegs[FirstReg + I];
4656 unsigned VReg = addLiveIn(MF, ArgReg, RC);
4657 unsigned Offset = I * GPRSizeInBytes;
4658 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
4659 DAG.getConstant(Offset, DL, PtrTy));
4660 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
4661 StorePtr, MachinePointerInfo(FuncArg, Offset));
4662 OutChains.push_back(Store);
4663 }
4664}
4665
4666// Copy byVal arg to registers and stack.
4667void MipsTargetLowering::passByValArg(
4668 SDValue Chain, const SDLoc &DL,
4669 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
4670 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
4671 MachineFrameInfo &MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
4672 unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
4673 const CCValAssign &VA) const {
4674 unsigned ByValSizeInBytes = Flags.getByValSize();
4675 unsigned OffsetInBytes = 0; // From beginning of struct
4676 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4678 std::min(Flags.getNonZeroByValAlign(), Align(RegSizeInBytes));
4679 EVT PtrTy = getPointerTy(DAG.getDataLayout()),
4680 RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4681 unsigned NumRegs = LastReg - FirstReg;
4682
4683 if (NumRegs) {
4684 ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs();
4685 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
4686 unsigned I = 0;
4687
4688 // Copy words to registers.
4689 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
4690 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4691 DAG.getConstant(OffsetInBytes, DL, PtrTy));
4692 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
4693 MachinePointerInfo(), Alignment);
4694 MemOpChains.push_back(LoadVal.getValue(1));
4695 unsigned ArgReg = ArgRegs[FirstReg + I];
4696 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
4697 }
4698
4699 // Return if the struct has been fully copied.
4700 if (ByValSizeInBytes == OffsetInBytes)
4701 return;
4702
4703 // Copy the remainder of the byval argument with sub-word loads and shifts.
4704 if (LeftoverBytes) {
4705 SDValue Val;
4706
4707 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
4708 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
4709 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
4710
4711 if (RemainingSizeInBytes < LoadSizeInBytes)
4712 continue;
4713
4714 // Load subword.
4715 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4716 DAG.getConstant(OffsetInBytes, DL,
4717 PtrTy));
4718 SDValue LoadVal = DAG.getExtLoad(
4719 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
4720 MVT::getIntegerVT(LoadSizeInBytes * 8), Alignment);
4721 MemOpChains.push_back(LoadVal.getValue(1));
4722
4723 // Shift the loaded value.
4724 unsigned Shamt;
4725
4726 if (isLittle)
4727 Shamt = TotalBytesLoaded * 8;
4728 else
4729 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
4730
4731 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
4732 DAG.getConstant(Shamt, DL, MVT::i32));
4733
4734 if (Val.getNode())
4735 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
4736 else
4737 Val = Shift;
4738
4739 OffsetInBytes += LoadSizeInBytes;
4740 TotalBytesLoaded += LoadSizeInBytes;
4741 Alignment = std::min(Alignment, Align(LoadSizeInBytes));
4742 }
4743
4744 unsigned ArgReg = ArgRegs[FirstReg + I];
4745 RegsToPass.push_back(std::make_pair(ArgReg, Val));
4746 return;
4747 }
4748 }
4749
4750 // Copy remainder of byval arg to it with memcpy.
4751 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
4752 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4753 DAG.getConstant(OffsetInBytes, DL, PtrTy));
4754 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
4756 Chain = DAG.getMemcpy(
4757 Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, DL, PtrTy), Alignment,
4758 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
4759 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(), MachinePointerInfo());
4760 MemOpChains.push_back(Chain);
4761}
4762
4763void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
4764 SDValue Chain, const SDLoc &DL,
4765 SelectionDAG &DAG,
4766 CCState &State) const {
4767 ArrayRef<MCPhysReg> ArgRegs = ABI.getVarArgRegs(Subtarget.isGP64bit());
4768 unsigned Idx = State.getFirstUnallocated(ArgRegs);
4769 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4770 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4771 const TargetRegisterClass *RC = getRegClassFor(RegTy);
4773 MachineFrameInfo &MFI = MF.getFrameInfo();
4774 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4775
4776 // Offset of the first variable argument from stack pointer.
4777 int VaArgOffset;
4778
4779 if (ArgRegs.size() == Idx)
4780 VaArgOffset = alignTo(State.getStackSize(), RegSizeInBytes);
4781 else {
4782 VaArgOffset =
4783 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
4784 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
4785 }
4786
4787 // Record the frame index of the first variable argument
4788 // which is a value necessary to VASTART.
4789 int FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4790 MipsFI->setVarArgsFrameIndex(FI);
4791
4792 // Copy the integer registers that have not been used for argument passing
4793 // to the argument register save area. For O32, the save area is allocated
4794 // in the caller's stack frame, while for N32/64, it is allocated in the
4795 // callee's stack frame.
4796 for (unsigned I = Idx; I < ArgRegs.size();
4797 ++I, VaArgOffset += RegSizeInBytes) {
4798 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
4799 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
4800 FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4801 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4802 SDValue Store =
4803 DAG.getStore(Chain, DL, ArgValue, PtrOff, MachinePointerInfo());
4804 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
4805 (Value *)nullptr);
4806 OutChains.push_back(Store);
4807 }
4808}
4809
4811 Align Alignment) const {
4812 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
4813
4814 assert(Size && "Byval argument's size shouldn't be 0.");
4815
4816 Alignment = std::min(Alignment, TFL->getStackAlign());
4817
4818 unsigned FirstReg = 0;
4819 unsigned NumRegs = 0;
4820
4821 if (State->getCallingConv() != CallingConv::Fast) {
4822 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4823 ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
4824 // FIXME: The O32 case actually describes no shadow registers.
4825 const MCPhysReg *ShadowRegs =
4826 ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
4827
4828 // We used to check the size as well but we can't do that anymore since
4829 // CCState::HandleByVal() rounds up the size after calling this function.
4830 assert(
4831 Alignment >= Align(RegSizeInBytes) &&
4832 "Byval argument's alignment should be a multiple of RegSizeInBytes.");
4833
4834 FirstReg = State->getFirstUnallocated(IntArgRegs);
4835
4836 // If Alignment > RegSizeInBytes, the first arg register must be even.
4837 // FIXME: This condition happens to do the right thing but it's not the
4838 // right way to test it. We want to check that the stack frame offset
4839 // of the register is aligned.
4840 if ((Alignment > RegSizeInBytes) && (FirstReg % 2)) {
4841 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
4842 ++FirstReg;
4843 }
4844
4845 // Mark the registers allocated.
4846 Size = alignTo(Size, RegSizeInBytes);
4847 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
4848 Size -= RegSizeInBytes, ++I, ++NumRegs)
4849 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
4850 }
4851
4852 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
4853}
4854
4855MachineBasicBlock *MipsTargetLowering::emitPseudoSELECT(MachineInstr &MI,
4857 bool isFPCmp,
4858 unsigned Opc) const {
4860 "Subtarget already supports SELECT nodes with the use of"
4861 "conditional-move instructions.");
4862
4863 const TargetInstrInfo *TII =
4865 DebugLoc DL = MI.getDebugLoc();
4866
4867 // To "insert" a SELECT instruction, we actually have to insert the
4868 // diamond control-flow pattern. The incoming instruction knows the
4869 // destination vreg to set, the condition code register to branch on, the
4870 // true/false values to select between, and a branch opcode to use.
4871 const BasicBlock *LLVM_BB = BB->getBasicBlock();
4873
4874 // thisMBB:
4875 // ...
4876 // TrueVal = ...
4877 // setcc r1, r2, r3
4878 // bNE r1, r0, copy1MBB
4879 // fallthrough --> copy0MBB
4880 MachineBasicBlock *thisMBB = BB;
4881 MachineFunction *F = BB->getParent();
4882 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4883 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
4884 F->insert(It, copy0MBB);
4885 F->insert(It, sinkMBB);
4886
4887 // Transfer the remainder of BB and its successor edges to sinkMBB.
4888 sinkMBB->splice(sinkMBB->begin(), BB,
4889 std::next(MachineBasicBlock::iterator(MI)), BB->end());
4891
4892 // Next, add the true and fallthrough blocks as its successors.
4893 BB->addSuccessor(copy0MBB);
4894 BB->addSuccessor(sinkMBB);
4895
4896 if (isFPCmp) {
4897 // bc1[tf] cc, sinkMBB
4898 BuildMI(BB, DL, TII->get(Opc))
4899 .addReg(MI.getOperand(1).getReg())
4900 .addMBB(sinkMBB);
4901 } else {
4902 // bne rs, $0, sinkMBB
4903 BuildMI(BB, DL, TII->get(Opc))
4904 .addReg(MI.getOperand(1).getReg())
4905 .addReg(Mips::ZERO)
4906 .addMBB(sinkMBB);
4907 }
4908
4909 // copy0MBB:
4910 // %FalseValue = ...
4911 // # fallthrough to sinkMBB
4912 BB = copy0MBB;
4913
4914 // Update machine-CFG edges
4915 BB->addSuccessor(sinkMBB);
4916
4917 // sinkMBB:
4918 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
4919 // ...
4920 BB = sinkMBB;
4921
4922 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(0).getReg())
4923 .addReg(MI.getOperand(2).getReg())
4924 .addMBB(thisMBB)
4925 .addReg(MI.getOperand(3).getReg())
4926 .addMBB(copy0MBB);
4927
4928 MI.eraseFromParent(); // The pseudo instruction is gone now.
4929
4930 return BB;
4931}
4932
4934MipsTargetLowering::emitPseudoD_SELECT(MachineInstr &MI,
4935 MachineBasicBlock *BB) const {
4936 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
4937 "Subtarget already supports SELECT nodes with the use of"
4938 "conditional-move instructions.");
4939
4940 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
4941 DebugLoc DL = MI.getDebugLoc();
4942
4943 // D_SELECT substitutes two SELECT nodes that goes one after another and
4944 // have the same condition operand. On machines which don't have
4945 // conditional-move instruction, it reduces unnecessary branch instructions
4946 // which are result of using two diamond patterns that are result of two
4947 // SELECT pseudo instructions.
4948 const BasicBlock *LLVM_BB = BB->getBasicBlock();
4950
4951 // thisMBB:
4952 // ...
4953 // TrueVal = ...
4954 // setcc r1, r2, r3
4955 // bNE r1, r0, copy1MBB
4956 // fallthrough --> copy0MBB
4957 MachineBasicBlock *thisMBB = BB;
4958 MachineFunction *F = BB->getParent();
4959 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4960 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
4961 F->insert(It, copy0MBB);
4962 F->insert(It, sinkMBB);
4963
4964 // Transfer the remainder of BB and its successor edges to sinkMBB.
4965 sinkMBB->splice(sinkMBB->begin(), BB,
4966 std::next(MachineBasicBlock::iterator(MI)), BB->end());
4968
4969 // Next, add the true and fallthrough blocks as its successors.
4970 BB->addSuccessor(copy0MBB);
4971 BB->addSuccessor(sinkMBB);
4972
4973 // bne rs, $0, sinkMBB
4974 BuildMI(BB, DL, TII->get(Mips::BNE))
4975 .addReg(MI.getOperand(2).getReg())
4976 .addReg(Mips::ZERO)
4977 .addMBB(sinkMBB);
4978
4979 // copy0MBB:
4980 // %FalseValue = ...
4981 // # fallthrough to sinkMBB
4982 BB = copy0MBB;
4983
4984 // Update machine-CFG edges
4985 BB->addSuccessor(sinkMBB);
4986
4987 // sinkMBB:
4988 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
4989 // ...
4990 BB = sinkMBB;
4991
4992 // Use two PHI nodes to select two reults
4993 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(0).getReg())
4994 .addReg(MI.getOperand(3).getReg())
4995 .addMBB(thisMBB)
4996 .addReg(MI.getOperand(5).getReg())
4997 .addMBB(copy0MBB);
4998 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(1).getReg())
4999 .addReg(MI.getOperand(4).getReg())
5000 .addMBB(thisMBB)
5001 .addReg(MI.getOperand(6).getReg())
5002 .addMBB(copy0MBB);
5003
5004 MI.eraseFromParent(); // The pseudo instruction is gone now.
5005
5006 return BB;
5007}
5008
5011 const MachineFunction &MF) const {
5012 StringRef Name(RegName);
5013 Name.consume_front("$");
5014
5015 unsigned RegIdx;
5016 if (Name.getAsInteger(10, RegIdx)) {
5017 std::string LowerName = Name.lower();
5018 const MCRegisterInfo &MRI = *MF.getContext().getRegisterInfo();
5019 int Index =
5020 MIPS_MC::getCPURegisterIndex(LowerName, MRI, ABI.getRegAltNameIndex());
5021 if (Index < 0)
5023 Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
5024 RegIdx = Index;
5025 }
5026
5027 if (RegIdx < 32) {
5028 const MCRegisterInfo *MRI = MF.getContext().getRegisterInfo();
5029 unsigned RegClassID = Mips::GPR32RegClassID;
5030 if (VT.isValid()) {
5031 if (VT.getSizeInBits() == 64) {
5032 if (!Subtarget.isGP64bit())
5033 report_fatal_error("64-bit registers not supported on 32-bit target");
5034 RegClassID = Mips::GPR64RegClassID;
5035 } else if (VT.getSizeInBits() == 32) {
5036 RegClassID = Mips::GPR32RegClassID;
5037 } else {
5038 report_fatal_error(Twine("Invalid register \"" + StringRef(RegName) +
5039 "\" for " + Twine(VT.getSizeInBits()) +
5040 "-bit type."));
5041 }
5042 } else if (Subtarget.isGP64bit()) {
5043 RegClassID = Mips::GPR64RegClassID;
5044 }
5045 const MCRegisterClass &RC = MRI->getRegClass(RegClassID);
5046 Register Reg = RC.getRegister(RegIdx);
5047 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
5048 if (!ReservedRegs.test(Reg))
5049 reportFatalUsageError(Twine("Trying to obtain non-reserved register \"" +
5050 StringRef(RegName) + "\"."));
5051 return Reg;
5052 }
5053
5055 Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
5056}
5057
5058MachineBasicBlock *MipsTargetLowering::emitLDR_W(MachineInstr &MI,
5059 MachineBasicBlock *BB) const {
5060 MachineFunction *MF = BB->getParent();
5061 MachineRegisterInfo &MRI = MF->getRegInfo();
5063 const bool IsLittle = Subtarget.isLittle();
5064 DebugLoc DL = MI.getDebugLoc();
5065
5066 Register Dest = MI.getOperand(0).getReg();
5067 Register Address = MI.getOperand(1).getReg();
5068 unsigned Imm = MI.getOperand(2).getImm();
5069
5071
5073 // Mips release 6 can load from adress that is not naturally-aligned.
5074 Register Temp = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5075 BuildMI(*BB, I, DL, TII->get(Mips::LW))
5076 .addDef(Temp)
5077 .addUse(Address)
5078 .addImm(Imm);
5079 BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Dest).addUse(Temp);
5080 } else {
5081 // Mips release 5 needs to use instructions that can load from an unaligned
5082 // memory address.
5083 Register LoadHalf = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5084 Register LoadFull = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5085 Register Undef = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5086 BuildMI(*BB, I, DL, TII->get(Mips::IMPLICIT_DEF)).addDef(Undef);
5087 BuildMI(*BB, I, DL, TII->get(Mips::LWR))
5088 .addDef(LoadHalf)
5089 .addUse(Address)
5090 .addImm(Imm + (IsLittle ? 0 : 3))
5091 .addUse(Undef);
5092 BuildMI(*BB, I, DL, TII->get(Mips::LWL))
5093 .addDef(LoadFull)
5094 .addUse(Address)
5095 .addImm(Imm + (IsLittle ? 3 : 0))
5096 .addUse(LoadHalf);
5097 BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Dest).addUse(LoadFull);
5098 }
5099
5100 MI.eraseFromParent();
5101 return BB;
5102}
5103
5104MachineBasicBlock *MipsTargetLowering::emitLDR_D(MachineInstr &MI,
5105 MachineBasicBlock *BB) const {
5106 MachineFunction *MF = BB->getParent();
5107 MachineRegisterInfo &MRI = MF->getRegInfo();
5108 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
5109 const bool IsLittle = Subtarget.isLittle();
5110 DebugLoc DL = MI.getDebugLoc();
5111
5112 Register Dest = MI.getOperand(0).getReg();
5113 Register Address = MI.getOperand(1).getReg();
5114 unsigned Imm = MI.getOperand(2).getImm();
5115
5117
5118 if (Subtarget.hasMips32r6() || Subtarget.hasMips64r6()) {
5119 // Mips release 6 can load from adress that is not naturally-aligned.
5120 if (Subtarget.isGP64bit()) {
5121 Register Temp = MRI.createVirtualRegister(&Mips::GPR64RegClass);
5122 BuildMI(*BB, I, DL, TII->get(Mips::LD))
5123 .addDef(Temp)
5124 .addUse(Address)
5125 .addImm(Imm);
5126 BuildMI(*BB, I, DL, TII->get(Mips::FILL_D)).addDef(Dest).addUse(Temp);
5127 } else {
5128 Register Wtemp = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
5129 Register Lo = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5130 Register Hi = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5131 BuildMI(*BB, I, DL, TII->get(Mips::LW))
5132 .addDef(Lo)
5133 .addUse(Address)
5134 .addImm(Imm + (IsLittle ? 0 : 4));
5135 BuildMI(*BB, I, DL, TII->get(Mips::LW))
5136 .addDef(Hi)
5137 .addUse(Address)
5138 .addImm(Imm + (IsLittle ? 4 : 0));
5139 BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Wtemp).addUse(Lo);
5140 BuildMI(*BB, I, DL, TII->get(Mips::INSERT_W), Dest)
5141 .addUse(Wtemp)
5142 .addUse(Hi)
5143 .addImm(1);
5144 }
5145 } else {
5146 // Mips release 5 needs to use instructions that can load from an unaligned
5147 // memory address.
5148 Register LoHalf = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5149 Register LoFull = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5150 Register LoUndef = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5151 Register HiHalf = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5152 Register HiFull = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5153 Register HiUndef = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5154 Register Wtemp = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
5155 BuildMI(*BB, I, DL, TII->get(Mips::IMPLICIT_DEF)).addDef(LoUndef);
5156 BuildMI(*BB, I, DL, TII->get(Mips::LWR))
5157 .addDef(LoHalf)
5158 .addUse(Address)
5159 .addImm(Imm + (IsLittle ? 0 : 7))
5160 .addUse(LoUndef);
5161 BuildMI(*BB, I, DL, TII->get(Mips::LWL))
5162 .addDef(LoFull)
5163 .addUse(Address)
5164 .addImm(Imm + (IsLittle ? 3 : 4))
5165 .addUse(LoHalf);
5166 BuildMI(*BB, I, DL, TII->get(Mips::IMPLICIT_DEF)).addDef(HiUndef);
5167 BuildMI(*BB, I, DL, TII->get(Mips::LWR))
5168 .addDef(HiHalf)
5169 .addUse(Address)
5170 .addImm(Imm + (IsLittle ? 4 : 3))
5171 .addUse(HiUndef);
5172 BuildMI(*BB, I, DL, TII->get(Mips::LWL))
5173 .addDef(HiFull)
5174 .addUse(Address)
5175 .addImm(Imm + (IsLittle ? 7 : 0))
5176 .addUse(HiHalf);
5177 BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Wtemp).addUse(LoFull);
5178 BuildMI(*BB, I, DL, TII->get(Mips::INSERT_W), Dest)
5179 .addUse(Wtemp)
5180 .addUse(HiFull)
5181 .addImm(1);
5182 }
5183
5184 MI.eraseFromParent();
5185 return BB;
5186}
5187
5188MachineBasicBlock *MipsTargetLowering::emitSTR_W(MachineInstr &MI,
5189 MachineBasicBlock *BB) const {
5190 MachineFunction *MF = BB->getParent();
5191 MachineRegisterInfo &MRI = MF->getRegInfo();
5192 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
5193 const bool IsLittle = Subtarget.isLittle();
5194 DebugLoc DL = MI.getDebugLoc();
5195
5196 Register StoreVal = MI.getOperand(0).getReg();
5197 Register Address = MI.getOperand(1).getReg();
5198 unsigned Imm = MI.getOperand(2).getImm();
5199
5201
5202 if (Subtarget.hasMips32r6() || Subtarget.hasMips64r6()) {
5203 // Mips release 6 can store to adress that is not naturally-aligned.
5204 Register BitcastW = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
5205 Register Tmp = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5206 BuildMI(*BB, I, DL, TII->get(Mips::COPY)).addDef(BitcastW).addUse(StoreVal);
5207 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
5208 .addDef(Tmp)
5209 .addUse(BitcastW)
5210 .addImm(0);
5211 BuildMI(*BB, I, DL, TII->get(Mips::SW))
5212 .addUse(Tmp)
5213 .addUse(Address)
5214 .addImm(Imm);
5215 } else {
5216 // Mips release 5 needs to use instructions that can store to an unaligned
5217 // memory address.
5218 Register Tmp = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5219 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
5220 .addDef(Tmp)
5221 .addUse(StoreVal)
5222 .addImm(0);
5223 BuildMI(*BB, I, DL, TII->get(Mips::SWR))
5224 .addUse(Tmp)
5225 .addUse(Address)
5226 .addImm(Imm + (IsLittle ? 0 : 3));
5227 BuildMI(*BB, I, DL, TII->get(Mips::SWL))
5228 .addUse(Tmp)
5229 .addUse(Address)
5230 .addImm(Imm + (IsLittle ? 3 : 0));
5231 }
5232
5233 MI.eraseFromParent();
5234
5235 return BB;
5236}
5237
5238MachineBasicBlock *MipsTargetLowering::emitSTR_D(MachineInstr &MI,
5239 MachineBasicBlock *BB) const {
5240 MachineFunction *MF = BB->getParent();
5241 MachineRegisterInfo &MRI = MF->getRegInfo();
5242 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
5243 const bool IsLittle = Subtarget.isLittle();
5244 DebugLoc DL = MI.getDebugLoc();
5245
5246 Register StoreVal = MI.getOperand(0).getReg();
5247 Register Address = MI.getOperand(1).getReg();
5248 unsigned Imm = MI.getOperand(2).getImm();
5249
5251
5252 if (Subtarget.hasMips32r6() || Subtarget.hasMips64r6()) {
5253 // Mips release 6 can store to adress that is not naturally-aligned.
5254 if (Subtarget.isGP64bit()) {
5255 Register BitcastD = MRI.createVirtualRegister(&Mips::MSA128DRegClass);
5256 Register Lo = MRI.createVirtualRegister(&Mips::GPR64RegClass);
5257 BuildMI(*BB, I, DL, TII->get(Mips::COPY))
5258 .addDef(BitcastD)
5259 .addUse(StoreVal);
5260 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_D))
5261 .addDef(Lo)
5262 .addUse(BitcastD)
5263 .addImm(0);
5264 BuildMI(*BB, I, DL, TII->get(Mips::SD))
5265 .addUse(Lo)
5266 .addUse(Address)
5267 .addImm(Imm);
5268 } else {
5269 Register BitcastW = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
5270 Register Lo = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5271 Register Hi = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5272 BuildMI(*BB, I, DL, TII->get(Mips::COPY))
5273 .addDef(BitcastW)
5274 .addUse(StoreVal);
5275 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
5276 .addDef(Lo)
5277 .addUse(BitcastW)
5278 .addImm(0);
5279 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
5280 .addDef(Hi)
5281 .addUse(BitcastW)
5282 .addImm(1);
5283 BuildMI(*BB, I, DL, TII->get(Mips::SW))
5284 .addUse(Lo)
5285 .addUse(Address)
5286 .addImm(Imm + (IsLittle ? 0 : 4));
5287 BuildMI(*BB, I, DL, TII->get(Mips::SW))
5288 .addUse(Hi)
5289 .addUse(Address)
5290 .addImm(Imm + (IsLittle ? 4 : 0));
5291 }
5292 } else {
5293 // Mips release 5 needs to use instructions that can store to an unaligned
5294 // memory address.
5295 Register Bitcast = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
5296 Register Lo = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5297 Register Hi = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5298 BuildMI(*BB, I, DL, TII->get(Mips::COPY)).addDef(Bitcast).addUse(StoreVal);
5299 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
5300 .addDef(Lo)
5301 .addUse(Bitcast)
5302 .addImm(0);
5303 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
5304 .addDef(Hi)
5305 .addUse(Bitcast)
5306 .addImm(1);
5307 BuildMI(*BB, I, DL, TII->get(Mips::SWR))
5308 .addUse(Lo)
5309 .addUse(Address)
5310 .addImm(Imm + (IsLittle ? 0 : 3));
5311 BuildMI(*BB, I, DL, TII->get(Mips::SWL))
5312 .addUse(Lo)
5313 .addUse(Address)
5314 .addImm(Imm + (IsLittle ? 3 : 0));
5315 BuildMI(*BB, I, DL, TII->get(Mips::SWR))
5316 .addUse(Hi)
5317 .addUse(Address)
5318 .addImm(Imm + (IsLittle ? 4 : 7));
5319 BuildMI(*BB, I, DL, TII->get(Mips::SWL))
5320 .addUse(Hi)
5321 .addUse(Address)
5322 .addImm(Imm + (IsLittle ? 7 : 4));
5323 }
5324
5325 MI.eraseFromParent();
5326 return BB;
5327}
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:734
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 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...
virtual void getOpndList(SmallVectorImpl< SDValue > &Ops, std::deque< std::pair< unsigned, SDValue > > &RegsToPass, bool IsPICCall, bool GlobalOrExternal, bool LocalLinkage, 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...
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.
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.
@ 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