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" 15 #include "MCTargetDesc/MipsBaseInfo.h" 16 #include "MCTargetDesc/MipsInstPrinter.h" 17 #include "MCTargetDesc/MipsMCTargetDesc.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" 24 #include "MipsTargetObjectFile.h" 25 #include "llvm/ADT/APFloat.h" 26 #include "llvm/ADT/ArrayRef.h" 27 #include "llvm/ADT/SmallVector.h" 28 #include "llvm/ADT/Statistic.h" 29 #include "llvm/ADT/StringRef.h" 30 #include "llvm/ADT/StringSwitch.h" 31 #include "llvm/CodeGen/CallingConvLower.h" 32 #include "llvm/CodeGen/FunctionLoweringInfo.h" 33 #include "llvm/CodeGen/ISDOpcodes.h" 34 #include "llvm/CodeGen/MachineBasicBlock.h" 35 #include "llvm/CodeGen/MachineFrameInfo.h" 36 #include "llvm/CodeGen/MachineFunction.h" 37 #include "llvm/CodeGen/MachineInstr.h" 38 #include "llvm/CodeGen/MachineInstrBuilder.h" 39 #include "llvm/CodeGen/MachineJumpTableInfo.h" 40 #include "llvm/CodeGen/MachineMemOperand.h" 41 #include "llvm/CodeGen/MachineOperand.h" 42 #include "llvm/CodeGen/MachineRegisterInfo.h" 43 #include "llvm/CodeGen/RuntimeLibcalls.h" 44 #include "llvm/CodeGen/SelectionDAG.h" 45 #include "llvm/CodeGen/SelectionDAGNodes.h" 46 #include "llvm/CodeGen/TargetFrameLowering.h" 47 #include "llvm/CodeGen/TargetInstrInfo.h" 48 #include "llvm/CodeGen/TargetRegisterInfo.h" 49 #include "llvm/CodeGen/ValueTypes.h" 50 #include "llvm/IR/CallingConv.h" 51 #include "llvm/IR/Constants.h" 52 #include "llvm/IR/DataLayout.h" 53 #include "llvm/IR/DebugLoc.h" 54 #include "llvm/IR/DerivedTypes.h" 55 #include "llvm/IR/Function.h" 56 #include "llvm/IR/GlobalValue.h" 57 #include "llvm/IR/Type.h" 58 #include "llvm/IR/Value.h" 59 #include "llvm/MC/MCContext.h" 60 #include "llvm/MC/MCRegisterInfo.h" 61 #include "llvm/Support/Casting.h" 62 #include "llvm/Support/CodeGen.h" 63 #include "llvm/Support/CommandLine.h" 64 #include "llvm/Support/Compiler.h" 65 #include "llvm/Support/ErrorHandling.h" 66 #include "llvm/Support/MachineValueType.h" 67 #include "llvm/Support/MathExtras.h" 68 #include "llvm/Target/TargetMachine.h" 69 #include "llvm/Target/TargetOptions.h" 70 #include <algorithm> 71 #include <cassert> 72 #include <cctype> 73 #include <cstdint> 74 #include <deque> 75 #include <iterator> 76 #include <utility> 77 #include <vector> 78 79 using namespace llvm; 80 81 #define DEBUG_TYPE "mips-lower" 82 83 STATISTIC(NumTailCalls, "Number of tail calls"); 84 85 static cl::opt<bool> 86 NoZeroDivCheck("mno-check-zero-division", cl::Hidden, 87 cl::desc("MIPS: Don't trap on integer division by zero."), 88 cl::init(false)); 89 90 extern cl::opt<bool> EmitJalrReloc; 91 92 static const MCPhysReg Mips64DPRegs[8] = { 93 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64, 94 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64 95 }; 96 97 // If I is a shifted mask, set the size (Size) and the first bit of the 98 // mask (Pos), and return true. 99 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11). 100 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) { 101 if (!isShiftedMask_64(I)) 102 return false; 103 104 Size = countPopulation(I); 105 Pos = countTrailingZeros(I); 106 return true; 107 } 108 109 // The MIPS MSA ABI passes vector arguments in the integer register set. 110 // The number of integer registers used is dependant on the ABI used. 111 MVT MipsTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 112 CallingConv::ID CC, 113 EVT VT) const { 114 if (!VT.isVector()) 115 return getRegisterType(Context, VT); 116 117 return Subtarget.isABI_O32() || VT.getSizeInBits() == 32 ? MVT::i32 118 : MVT::i64; 119 } 120 121 unsigned MipsTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 122 CallingConv::ID CC, 123 EVT VT) const { 124 if (VT.isVector()) 125 return std::max(((unsigned)VT.getSizeInBits() / 126 (Subtarget.isABI_O32() ? 32 : 64)), 127 1U); 128 return MipsTargetLowering::getNumRegisters(Context, VT); 129 } 130 131 unsigned MipsTargetLowering::getVectorTypeBreakdownForCallingConv( 132 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, 133 unsigned &NumIntermediates, MVT &RegisterVT) const { 134 // Break down vector types to either 2 i64s or 4 i32s. 135 RegisterVT = getRegisterTypeForCallingConv(Context, CC, VT); 136 IntermediateVT = RegisterVT; 137 NumIntermediates = VT.getSizeInBits() < RegisterVT.getSizeInBits() 138 ? VT.getVectorNumElements() 139 : VT.getSizeInBits() / RegisterVT.getSizeInBits(); 140 141 return NumIntermediates; 142 } 143 144 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const { 145 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>(); 146 return DAG.getRegister(FI->getGlobalBaseReg(), Ty); 147 } 148 149 SDValue 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 155 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty, 156 SelectionDAG &DAG, 157 unsigned Flag) const { 158 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag); 159 } 160 161 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty, 162 SelectionDAG &DAG, 163 unsigned Flag) const { 164 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag); 165 } 166 167 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty, 168 SelectionDAG &DAG, 169 unsigned Flag) const { 170 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag); 171 } 172 173 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty, 174 SelectionDAG &DAG, 175 unsigned Flag) const { 176 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(), 177 N->getOffset(), Flag); 178 } 179 180 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const { 181 switch ((MipsISD::NodeType)Opcode) { 182 case MipsISD::FIRST_NUMBER: break; 183 case MipsISD::JmpLink: return "MipsISD::JmpLink"; 184 case MipsISD::TailCall: return "MipsISD::TailCall"; 185 case MipsISD::Highest: return "MipsISD::Highest"; 186 case MipsISD::Higher: return "MipsISD::Higher"; 187 case MipsISD::Hi: return "MipsISD::Hi"; 188 case MipsISD::Lo: return "MipsISD::Lo"; 189 case MipsISD::GotHi: return "MipsISD::GotHi"; 190 case MipsISD::TlsHi: return "MipsISD::TlsHi"; 191 case MipsISD::GPRel: return "MipsISD::GPRel"; 192 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer"; 193 case MipsISD::Ret: return "MipsISD::Ret"; 194 case MipsISD::ERet: return "MipsISD::ERet"; 195 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN"; 196 case MipsISD::FMS: return "MipsISD::FMS"; 197 case MipsISD::FPBrcond: return "MipsISD::FPBrcond"; 198 case MipsISD::FPCmp: return "MipsISD::FPCmp"; 199 case MipsISD::FSELECT: return "MipsISD::FSELECT"; 200 case MipsISD::MTC1_D64: return "MipsISD::MTC1_D64"; 201 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T"; 202 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F"; 203 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP"; 204 case MipsISD::MFHI: return "MipsISD::MFHI"; 205 case MipsISD::MFLO: return "MipsISD::MFLO"; 206 case MipsISD::MTLOHI: return "MipsISD::MTLOHI"; 207 case MipsISD::Mult: return "MipsISD::Mult"; 208 case MipsISD::Multu: return "MipsISD::Multu"; 209 case MipsISD::MAdd: return "MipsISD::MAdd"; 210 case MipsISD::MAddu: return "MipsISD::MAddu"; 211 case MipsISD::MSub: return "MipsISD::MSub"; 212 case MipsISD::MSubu: return "MipsISD::MSubu"; 213 case MipsISD::DivRem: return "MipsISD::DivRem"; 214 case MipsISD::DivRemU: return "MipsISD::DivRemU"; 215 case MipsISD::DivRem16: return "MipsISD::DivRem16"; 216 case MipsISD::DivRemU16: return "MipsISD::DivRemU16"; 217 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64"; 218 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64"; 219 case MipsISD::Wrapper: return "MipsISD::Wrapper"; 220 case MipsISD::DynAlloc: return "MipsISD::DynAlloc"; 221 case MipsISD::Sync: return "MipsISD::Sync"; 222 case MipsISD::Ext: return "MipsISD::Ext"; 223 case MipsISD::Ins: return "MipsISD::Ins"; 224 case MipsISD::CIns: return "MipsISD::CIns"; 225 case MipsISD::LWL: return "MipsISD::LWL"; 226 case MipsISD::LWR: return "MipsISD::LWR"; 227 case MipsISD::SWL: return "MipsISD::SWL"; 228 case MipsISD::SWR: return "MipsISD::SWR"; 229 case MipsISD::LDL: return "MipsISD::LDL"; 230 case MipsISD::LDR: return "MipsISD::LDR"; 231 case MipsISD::SDL: return "MipsISD::SDL"; 232 case MipsISD::SDR: return "MipsISD::SDR"; 233 case MipsISD::EXTP: return "MipsISD::EXTP"; 234 case MipsISD::EXTPDP: return "MipsISD::EXTPDP"; 235 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H"; 236 case MipsISD::EXTR_W: return "MipsISD::EXTR_W"; 237 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W"; 238 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W"; 239 case MipsISD::SHILO: return "MipsISD::SHILO"; 240 case MipsISD::MTHLIP: return "MipsISD::MTHLIP"; 241 case MipsISD::MULSAQ_S_W_PH: return "MipsISD::MULSAQ_S_W_PH"; 242 case MipsISD::MAQ_S_W_PHL: return "MipsISD::MAQ_S_W_PHL"; 243 case MipsISD::MAQ_S_W_PHR: return "MipsISD::MAQ_S_W_PHR"; 244 case MipsISD::MAQ_SA_W_PHL: return "MipsISD::MAQ_SA_W_PHL"; 245 case MipsISD::MAQ_SA_W_PHR: return "MipsISD::MAQ_SA_W_PHR"; 246 case MipsISD::DPAU_H_QBL: return "MipsISD::DPAU_H_QBL"; 247 case MipsISD::DPAU_H_QBR: return "MipsISD::DPAU_H_QBR"; 248 case MipsISD::DPSU_H_QBL: return "MipsISD::DPSU_H_QBL"; 249 case MipsISD::DPSU_H_QBR: return "MipsISD::DPSU_H_QBR"; 250 case MipsISD::DPAQ_S_W_PH: return "MipsISD::DPAQ_S_W_PH"; 251 case MipsISD::DPSQ_S_W_PH: return "MipsISD::DPSQ_S_W_PH"; 252 case MipsISD::DPAQ_SA_L_W: return "MipsISD::DPAQ_SA_L_W"; 253 case MipsISD::DPSQ_SA_L_W: return "MipsISD::DPSQ_SA_L_W"; 254 case MipsISD::DPA_W_PH: return "MipsISD::DPA_W_PH"; 255 case MipsISD::DPS_W_PH: return "MipsISD::DPS_W_PH"; 256 case MipsISD::DPAQX_S_W_PH: return "MipsISD::DPAQX_S_W_PH"; 257 case MipsISD::DPAQX_SA_W_PH: return "MipsISD::DPAQX_SA_W_PH"; 258 case MipsISD::DPAX_W_PH: return "MipsISD::DPAX_W_PH"; 259 case MipsISD::DPSX_W_PH: return "MipsISD::DPSX_W_PH"; 260 case MipsISD::DPSQX_S_W_PH: return "MipsISD::DPSQX_S_W_PH"; 261 case MipsISD::DPSQX_SA_W_PH: return "MipsISD::DPSQX_SA_W_PH"; 262 case MipsISD::MULSA_W_PH: return "MipsISD::MULSA_W_PH"; 263 case MipsISD::MULT: return "MipsISD::MULT"; 264 case MipsISD::MULTU: return "MipsISD::MULTU"; 265 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP"; 266 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP"; 267 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP"; 268 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP"; 269 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP"; 270 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP"; 271 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP"; 272 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP"; 273 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP"; 274 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO"; 275 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO"; 276 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO"; 277 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO"; 278 case MipsISD::VCEQ: return "MipsISD::VCEQ"; 279 case MipsISD::VCLE_S: return "MipsISD::VCLE_S"; 280 case MipsISD::VCLE_U: return "MipsISD::VCLE_U"; 281 case MipsISD::VCLT_S: return "MipsISD::VCLT_S"; 282 case MipsISD::VCLT_U: return "MipsISD::VCLT_U"; 283 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT"; 284 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT"; 285 case MipsISD::VNOR: return "MipsISD::VNOR"; 286 case MipsISD::VSHF: return "MipsISD::VSHF"; 287 case MipsISD::SHF: return "MipsISD::SHF"; 288 case MipsISD::ILVEV: return "MipsISD::ILVEV"; 289 case MipsISD::ILVOD: return "MipsISD::ILVOD"; 290 case MipsISD::ILVL: return "MipsISD::ILVL"; 291 case MipsISD::ILVR: return "MipsISD::ILVR"; 292 case MipsISD::PCKEV: return "MipsISD::PCKEV"; 293 case MipsISD::PCKOD: return "MipsISD::PCKOD"; 294 case MipsISD::INSVE: return "MipsISD::INSVE"; 295 } 296 return nullptr; 297 } 298 299 MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM, 300 const MipsSubtarget &STI) 301 : TargetLowering(TM), Subtarget(STI), ABI(TM.getABI()) { 302 // Mips does not have i1 type, so use i32 for 303 // setcc operations results (slt, sgt, ...). 304 setBooleanContents(ZeroOrOneBooleanContent); 305 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 306 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA 307 // does. Integer booleans still use 0 and 1. 308 if (Subtarget.hasMips32r6()) 309 setBooleanContents(ZeroOrOneBooleanContent, 310 ZeroOrNegativeOneBooleanContent); 311 312 // Load extented operations for i1 types must be promoted 313 for (MVT VT : MVT::integer_valuetypes()) { 314 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote); 315 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 316 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 317 } 318 319 // MIPS doesn't have extending float->double load/store. Set LoadExtAction 320 // for f32, f16 321 for (MVT VT : MVT::fp_valuetypes()) { 322 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 323 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 324 } 325 326 // Set LoadExtAction for f16 vectors to Expand 327 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 328 MVT F16VT = MVT::getVectorVT(MVT::f16, VT.getVectorNumElements()); 329 if (F16VT.isValid()) 330 setLoadExtAction(ISD::EXTLOAD, VT, F16VT, Expand); 331 } 332 333 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 334 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 335 336 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 337 338 // Used by legalize types to correctly generate the setcc result. 339 // Without this, every float setcc comes with a AND/OR with the result, 340 // we don't want this, since the fpcmp result goes to a flag register, 341 // which is used implicitly by brcond and select operations. 342 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 343 344 // Mips Custom Operations 345 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 346 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 347 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 348 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 349 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 350 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 351 setOperationAction(ISD::SELECT, MVT::f32, Custom); 352 setOperationAction(ISD::SELECT, MVT::f64, Custom); 353 setOperationAction(ISD::SELECT, MVT::i32, Custom); 354 setOperationAction(ISD::SETCC, MVT::f32, Custom); 355 setOperationAction(ISD::SETCC, MVT::f64, Custom); 356 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 357 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 358 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 359 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 360 361 if (!(TM.Options.NoNaNsFPMath || Subtarget.inAbs2008Mode())) { 362 setOperationAction(ISD::FABS, MVT::f32, Custom); 363 setOperationAction(ISD::FABS, MVT::f64, Custom); 364 } 365 366 if (Subtarget.isGP64bit()) { 367 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 368 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 369 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 370 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 371 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 372 setOperationAction(ISD::SELECT, MVT::i64, Custom); 373 setOperationAction(ISD::LOAD, MVT::i64, Custom); 374 setOperationAction(ISD::STORE, MVT::i64, Custom); 375 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 376 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 377 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 378 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 379 } 380 381 if (!Subtarget.isGP64bit()) { 382 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 383 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 384 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 385 } 386 387 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 388 if (Subtarget.isGP64bit()) 389 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 390 391 setOperationAction(ISD::SDIV, MVT::i32, Expand); 392 setOperationAction(ISD::SREM, MVT::i32, Expand); 393 setOperationAction(ISD::UDIV, MVT::i32, Expand); 394 setOperationAction(ISD::UREM, MVT::i32, Expand); 395 setOperationAction(ISD::SDIV, MVT::i64, Expand); 396 setOperationAction(ISD::SREM, MVT::i64, Expand); 397 setOperationAction(ISD::UDIV, MVT::i64, Expand); 398 setOperationAction(ISD::UREM, MVT::i64, Expand); 399 400 // Operations not directly supported by Mips. 401 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 402 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 403 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 404 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 405 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 406 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 407 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 408 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 409 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 410 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 411 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 412 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 413 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 414 if (Subtarget.hasCnMips()) { 415 setOperationAction(ISD::CTPOP, MVT::i32, Legal); 416 setOperationAction(ISD::CTPOP, MVT::i64, Legal); 417 } else { 418 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 419 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 420 } 421 setOperationAction(ISD::CTTZ, MVT::i32, Expand); 422 setOperationAction(ISD::CTTZ, MVT::i64, Expand); 423 setOperationAction(ISD::ROTL, MVT::i32, Expand); 424 setOperationAction(ISD::ROTL, MVT::i64, Expand); 425 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 426 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand); 427 428 if (!Subtarget.hasMips32r2()) 429 setOperationAction(ISD::ROTR, MVT::i32, Expand); 430 431 if (!Subtarget.hasMips64r2()) 432 setOperationAction(ISD::ROTR, MVT::i64, Expand); 433 434 setOperationAction(ISD::FSIN, MVT::f32, Expand); 435 setOperationAction(ISD::FSIN, MVT::f64, Expand); 436 setOperationAction(ISD::FCOS, MVT::f32, Expand); 437 setOperationAction(ISD::FCOS, MVT::f64, Expand); 438 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 439 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 440 setOperationAction(ISD::FPOW, MVT::f32, Expand); 441 setOperationAction(ISD::FPOW, MVT::f64, Expand); 442 setOperationAction(ISD::FLOG, MVT::f32, Expand); 443 setOperationAction(ISD::FLOG2, MVT::f32, Expand); 444 setOperationAction(ISD::FLOG10, MVT::f32, Expand); 445 setOperationAction(ISD::FEXP, MVT::f32, Expand); 446 setOperationAction(ISD::FMA, MVT::f32, Expand); 447 setOperationAction(ISD::FMA, MVT::f64, Expand); 448 setOperationAction(ISD::FREM, MVT::f32, Expand); 449 setOperationAction(ISD::FREM, MVT::f64, Expand); 450 451 // Lower f16 conversion operations into library calls 452 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 453 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 454 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 455 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 456 457 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom); 458 459 setOperationAction(ISD::VASTART, MVT::Other, Custom); 460 setOperationAction(ISD::VAARG, MVT::Other, Custom); 461 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 462 setOperationAction(ISD::VAEND, MVT::Other, Expand); 463 464 // Use the default for now 465 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 466 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 467 468 if (!Subtarget.isGP64bit()) { 469 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 470 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 471 } 472 473 if (!Subtarget.hasMips32r2()) { 474 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 475 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 476 } 477 478 // MIPS16 lacks MIPS32's clz and clo instructions. 479 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode()) 480 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 481 if (!Subtarget.hasMips64()) 482 setOperationAction(ISD::CTLZ, MVT::i64, Expand); 483 484 if (!Subtarget.hasMips32r2()) 485 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 486 if (!Subtarget.hasMips64r2()) 487 setOperationAction(ISD::BSWAP, MVT::i64, Expand); 488 489 if (Subtarget.isGP64bit()) { 490 setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Custom); 491 setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Custom); 492 setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Custom); 493 setTruncStoreAction(MVT::i64, MVT::i32, Custom); 494 } 495 496 setOperationAction(ISD::TRAP, MVT::Other, Legal); 497 498 setTargetDAGCombine(ISD::SDIVREM); 499 setTargetDAGCombine(ISD::UDIVREM); 500 setTargetDAGCombine(ISD::SELECT); 501 setTargetDAGCombine(ISD::AND); 502 setTargetDAGCombine(ISD::OR); 503 setTargetDAGCombine(ISD::ADD); 504 setTargetDAGCombine(ISD::SUB); 505 setTargetDAGCombine(ISD::AssertZext); 506 setTargetDAGCombine(ISD::SHL); 507 508 if (ABI.IsO32()) { 509 // These libcalls are not available in 32-bit. 510 setLibcallName(RTLIB::SHL_I128, nullptr); 511 setLibcallName(RTLIB::SRL_I128, nullptr); 512 setLibcallName(RTLIB::SRA_I128, nullptr); 513 } 514 515 setMinFunctionAlignment(Subtarget.isGP64bit() ? Align(8) : Align(4)); 516 517 // The arguments on the stack are defined in terms of 4-byte slots on O32 518 // and 8-byte slots on N32/N64. 519 setMinStackArgumentAlignment((ABI.IsN32() || ABI.IsN64()) ? Align(8) 520 : Align(4)); 521 522 setStackPointerRegisterToSaveRestore(ABI.IsN64() ? Mips::SP_64 : Mips::SP); 523 524 MaxStoresPerMemcpy = 16; 525 526 isMicroMips = Subtarget.inMicroMipsMode(); 527 } 528 529 const MipsTargetLowering * 530 MipsTargetLowering::create(const MipsTargetMachine &TM, 531 const MipsSubtarget &STI) { 532 if (STI.inMips16Mode()) 533 return createMips16TargetLowering(TM, STI); 534 535 return createMipsSETargetLowering(TM, STI); 536 } 537 538 // Create a fast isel object. 539 FastISel * 540 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 541 const TargetLibraryInfo *libInfo) const { 542 const MipsTargetMachine &TM = 543 static_cast<const MipsTargetMachine &>(funcInfo.MF->getTarget()); 544 545 // We support only the standard encoding [MIPS32,MIPS32R5] ISAs. 546 bool UseFastISel = TM.Options.EnableFastISel && Subtarget.hasMips32() && 547 !Subtarget.hasMips32r6() && !Subtarget.inMips16Mode() && 548 !Subtarget.inMicroMipsMode(); 549 550 // Disable if either of the following is true: 551 // We do not generate PIC, the ABI is not O32, XGOT is being used. 552 if (!TM.isPositionIndependent() || !TM.getABI().IsO32() || 553 Subtarget.useXGOT()) 554 UseFastISel = false; 555 556 return UseFastISel ? Mips::createFastISel(funcInfo, libInfo) : nullptr; 557 } 558 559 EVT MipsTargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &, 560 EVT VT) const { 561 if (!VT.isVector()) 562 return MVT::i32; 563 return VT.changeVectorElementTypeToInteger(); 564 } 565 566 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG, 567 TargetLowering::DAGCombinerInfo &DCI, 568 const MipsSubtarget &Subtarget) { 569 if (DCI.isBeforeLegalizeOps()) 570 return SDValue(); 571 572 EVT Ty = N->getValueType(0); 573 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64; 574 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64; 575 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 : 576 MipsISD::DivRemU16; 577 SDLoc DL(N); 578 579 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue, 580 N->getOperand(0), N->getOperand(1)); 581 SDValue InChain = DAG.getEntryNode(); 582 SDValue InGlue = DivRem; 583 584 // insert MFLO 585 if (N->hasAnyUseOfValue(0)) { 586 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty, 587 InGlue); 588 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo); 589 InChain = CopyFromLo.getValue(1); 590 InGlue = CopyFromLo.getValue(2); 591 } 592 593 // insert MFHI 594 if (N->hasAnyUseOfValue(1)) { 595 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL, 596 HI, Ty, InGlue); 597 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi); 598 } 599 600 return SDValue(); 601 } 602 603 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) { 604 switch (CC) { 605 default: llvm_unreachable("Unknown fp condition code!"); 606 case ISD::SETEQ: 607 case ISD::SETOEQ: return Mips::FCOND_OEQ; 608 case ISD::SETUNE: return Mips::FCOND_UNE; 609 case ISD::SETLT: 610 case ISD::SETOLT: return Mips::FCOND_OLT; 611 case ISD::SETGT: 612 case ISD::SETOGT: return Mips::FCOND_OGT; 613 case ISD::SETLE: 614 case ISD::SETOLE: return Mips::FCOND_OLE; 615 case ISD::SETGE: 616 case ISD::SETOGE: return Mips::FCOND_OGE; 617 case ISD::SETULT: return Mips::FCOND_ULT; 618 case ISD::SETULE: return Mips::FCOND_ULE; 619 case ISD::SETUGT: return Mips::FCOND_UGT; 620 case ISD::SETUGE: return Mips::FCOND_UGE; 621 case ISD::SETUO: return Mips::FCOND_UN; 622 case ISD::SETO: return Mips::FCOND_OR; 623 case ISD::SETNE: 624 case ISD::SETONE: return Mips::FCOND_ONE; 625 case ISD::SETUEQ: return Mips::FCOND_UEQ; 626 } 627 } 628 629 /// This function returns true if the floating point conditional branches and 630 /// conditional moves which use condition code CC should be inverted. 631 static bool invertFPCondCodeUser(Mips::CondCode CC) { 632 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT) 633 return false; 634 635 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) && 636 "Illegal Condition Code"); 637 638 return true; 639 } 640 641 // Creates and returns an FPCmp node from a setcc node. 642 // Returns Op if setcc is not a floating point comparison. 643 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) { 644 // must be a SETCC node 645 if (Op.getOpcode() != ISD::SETCC) 646 return Op; 647 648 SDValue LHS = Op.getOperand(0); 649 650 if (!LHS.getValueType().isFloatingPoint()) 651 return Op; 652 653 SDValue RHS = Op.getOperand(1); 654 SDLoc DL(Op); 655 656 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of 657 // node if necessary. 658 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 659 660 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS, 661 DAG.getConstant(condCodeToFCC(CC), DL, MVT::i32)); 662 } 663 664 // Creates and returns a CMovFPT/F node. 665 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True, 666 SDValue False, const SDLoc &DL) { 667 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2)); 668 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue()); 669 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32); 670 671 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL, 672 True.getValueType(), True, FCC0, False, Cond); 673 } 674 675 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG, 676 TargetLowering::DAGCombinerInfo &DCI, 677 const MipsSubtarget &Subtarget) { 678 if (DCI.isBeforeLegalizeOps()) 679 return SDValue(); 680 681 SDValue SetCC = N->getOperand(0); 682 683 if ((SetCC.getOpcode() != ISD::SETCC) || 684 !SetCC.getOperand(0).getValueType().isInteger()) 685 return SDValue(); 686 687 SDValue False = N->getOperand(2); 688 EVT FalseTy = False.getValueType(); 689 690 if (!FalseTy.isInteger()) 691 return SDValue(); 692 693 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False); 694 695 // If the RHS (False) is 0, we swap the order of the operands 696 // of ISD::SELECT (obviously also inverting the condition) so that we can 697 // take advantage of conditional moves using the $0 register. 698 // Example: 699 // return (a != 0) ? x : 0; 700 // load $reg, x 701 // movz $reg, $0, a 702 if (!FalseC) 703 return SDValue(); 704 705 const SDLoc DL(N); 706 707 if (!FalseC->getZExtValue()) { 708 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get(); 709 SDValue True = N->getOperand(1); 710 711 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0), 712 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true)); 713 714 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True); 715 } 716 717 // If both operands are integer constants there's a possibility that we 718 // can do some interesting optimizations. 719 SDValue True = N->getOperand(1); 720 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True); 721 722 if (!TrueC || !True.getValueType().isInteger()) 723 return SDValue(); 724 725 // We'll also ignore MVT::i64 operands as this optimizations proves 726 // to be ineffective because of the required sign extensions as the result 727 // of a SETCC operator is always MVT::i32 for non-vector types. 728 if (True.getValueType() == MVT::i64) 729 return SDValue(); 730 731 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue(); 732 733 // 1) (a < x) ? y : y-1 734 // slti $reg1, a, x 735 // addiu $reg2, $reg1, y-1 736 if (Diff == 1) 737 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False); 738 739 // 2) (a < x) ? y-1 : y 740 // slti $reg1, a, x 741 // xor $reg1, $reg1, 1 742 // addiu $reg2, $reg1, y-1 743 if (Diff == -1) { 744 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get(); 745 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0), 746 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true)); 747 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True); 748 } 749 750 // Could not optimize. 751 return SDValue(); 752 } 753 754 static SDValue performCMovFPCombine(SDNode *N, SelectionDAG &DAG, 755 TargetLowering::DAGCombinerInfo &DCI, 756 const MipsSubtarget &Subtarget) { 757 if (DCI.isBeforeLegalizeOps()) 758 return SDValue(); 759 760 SDValue ValueIfTrue = N->getOperand(0), ValueIfFalse = N->getOperand(2); 761 762 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(ValueIfFalse); 763 if (!FalseC || FalseC->getZExtValue()) 764 return SDValue(); 765 766 // Since RHS (False) is 0, we swap the order of the True/False operands 767 // (obviously also inverting the condition) so that we can 768 // take advantage of conditional moves using the $0 register. 769 // Example: 770 // return (a != 0) ? x : 0; 771 // load $reg, x 772 // movz $reg, $0, a 773 unsigned Opc = (N->getOpcode() == MipsISD::CMovFP_T) ? MipsISD::CMovFP_F : 774 MipsISD::CMovFP_T; 775 776 SDValue FCC = N->getOperand(1), Glue = N->getOperand(3); 777 return DAG.getNode(Opc, SDLoc(N), ValueIfFalse.getValueType(), 778 ValueIfFalse, FCC, ValueIfTrue, Glue); 779 } 780 781 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG, 782 TargetLowering::DAGCombinerInfo &DCI, 783 const MipsSubtarget &Subtarget) { 784 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert()) 785 return SDValue(); 786 787 SDValue FirstOperand = N->getOperand(0); 788 unsigned FirstOperandOpc = FirstOperand.getOpcode(); 789 SDValue Mask = N->getOperand(1); 790 EVT ValTy = N->getValueType(0); 791 SDLoc DL(N); 792 793 uint64_t Pos = 0, SMPos, SMSize; 794 ConstantSDNode *CN; 795 SDValue NewOperand; 796 unsigned Opc; 797 798 // Op's second operand must be a shifted mask. 799 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) || 800 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize)) 801 return SDValue(); 802 803 if (FirstOperandOpc == ISD::SRA || FirstOperandOpc == ISD::SRL) { 804 // Pattern match EXT. 805 // $dst = and ((sra or srl) $src , pos), (2**size - 1) 806 // => ext $dst, $src, pos, size 807 808 // The second operand of the shift must be an immediate. 809 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1)))) 810 return SDValue(); 811 812 Pos = CN->getZExtValue(); 813 814 // Return if the shifted mask does not start at bit 0 or the sum of its size 815 // and Pos exceeds the word's size. 816 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits()) 817 return SDValue(); 818 819 Opc = MipsISD::Ext; 820 NewOperand = FirstOperand.getOperand(0); 821 } else if (FirstOperandOpc == ISD::SHL && Subtarget.hasCnMips()) { 822 // Pattern match CINS. 823 // $dst = and (shl $src , pos), mask 824 // => cins $dst, $src, pos, size 825 // mask is a shifted mask with consecutive 1's, pos = shift amount, 826 // size = population count. 827 828 // The second operand of the shift must be an immediate. 829 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1)))) 830 return SDValue(); 831 832 Pos = CN->getZExtValue(); 833 834 if (SMPos != Pos || Pos >= ValTy.getSizeInBits() || SMSize >= 32 || 835 Pos + SMSize > ValTy.getSizeInBits()) 836 return SDValue(); 837 838 NewOperand = FirstOperand.getOperand(0); 839 // SMSize is 'location' (position) in this case, not size. 840 SMSize--; 841 Opc = MipsISD::CIns; 842 } else { 843 // Pattern match EXT. 844 // $dst = and $src, (2**size - 1) , if size > 16 845 // => ext $dst, $src, pos, size , pos = 0 846 847 // If the mask is <= 0xffff, andi can be used instead. 848 if (CN->getZExtValue() <= 0xffff) 849 return SDValue(); 850 851 // Return if the mask doesn't start at position 0. 852 if (SMPos) 853 return SDValue(); 854 855 Opc = MipsISD::Ext; 856 NewOperand = FirstOperand; 857 } 858 return DAG.getNode(Opc, DL, ValTy, NewOperand, 859 DAG.getConstant(Pos, DL, MVT::i32), 860 DAG.getConstant(SMSize, DL, MVT::i32)); 861 } 862 863 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 864 TargetLowering::DAGCombinerInfo &DCI, 865 const MipsSubtarget &Subtarget) { 866 // Pattern match INS. 867 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1), 868 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1 869 // => ins $dst, $src, size, pos, $src1 870 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert()) 871 return SDValue(); 872 873 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1); 874 uint64_t SMPos0, SMSize0, SMPos1, SMSize1; 875 ConstantSDNode *CN, *CN1; 876 877 // See if Op's first operand matches (and $src1 , mask0). 878 if (And0.getOpcode() != ISD::AND) 879 return SDValue(); 880 881 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) || 882 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0)) 883 return SDValue(); 884 885 // See if Op's second operand matches (and (shl $src, pos), mask1). 886 if (And1.getOpcode() == ISD::AND && 887 And1.getOperand(0).getOpcode() == ISD::SHL) { 888 889 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) || 890 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1)) 891 return SDValue(); 892 893 // The shift masks must have the same position and size. 894 if (SMPos0 != SMPos1 || SMSize0 != SMSize1) 895 return SDValue(); 896 897 SDValue Shl = And1.getOperand(0); 898 899 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1)))) 900 return SDValue(); 901 902 unsigned Shamt = CN->getZExtValue(); 903 904 // Return if the shift amount and the first bit position of mask are not the 905 // same. 906 EVT ValTy = N->getValueType(0); 907 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits())) 908 return SDValue(); 909 910 SDLoc DL(N); 911 return DAG.getNode(MipsISD::Ins, DL, ValTy, Shl.getOperand(0), 912 DAG.getConstant(SMPos0, DL, MVT::i32), 913 DAG.getConstant(SMSize0, DL, MVT::i32), 914 And0.getOperand(0)); 915 } else { 916 // Pattern match DINS. 917 // $dst = or (and $src, mask0), mask1 918 // where mask0 = ((1 << SMSize0) -1) << SMPos0 919 // => dins $dst, $src, pos, size 920 if (~CN->getSExtValue() == ((((int64_t)1 << SMSize0) - 1) << SMPos0) && 921 ((SMSize0 + SMPos0 <= 64 && Subtarget.hasMips64r2()) || 922 (SMSize0 + SMPos0 <= 32))) { 923 // Check if AND instruction has constant as argument 924 bool isConstCase = And1.getOpcode() != ISD::AND; 925 if (And1.getOpcode() == ISD::AND) { 926 if (!(CN1 = dyn_cast<ConstantSDNode>(And1->getOperand(1)))) 927 return SDValue(); 928 } else { 929 if (!(CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)))) 930 return SDValue(); 931 } 932 // Don't generate INS if constant OR operand doesn't fit into bits 933 // cleared by constant AND operand. 934 if (CN->getSExtValue() & CN1->getSExtValue()) 935 return SDValue(); 936 937 SDLoc DL(N); 938 EVT ValTy = N->getOperand(0)->getValueType(0); 939 SDValue Const1; 940 SDValue SrlX; 941 if (!isConstCase) { 942 Const1 = DAG.getConstant(SMPos0, DL, MVT::i32); 943 SrlX = DAG.getNode(ISD::SRL, DL, And1->getValueType(0), And1, Const1); 944 } 945 return DAG.getNode( 946 MipsISD::Ins, DL, N->getValueType(0), 947 isConstCase 948 ? DAG.getConstant(CN1->getSExtValue() >> SMPos0, DL, ValTy) 949 : SrlX, 950 DAG.getConstant(SMPos0, DL, MVT::i32), 951 DAG.getConstant(ValTy.getSizeInBits() / 8 < 8 ? SMSize0 & 31 952 : SMSize0, 953 DL, MVT::i32), 954 And0->getOperand(0)); 955 956 } 957 return SDValue(); 958 } 959 } 960 961 static SDValue performMADD_MSUBCombine(SDNode *ROOTNode, SelectionDAG &CurDAG, 962 const MipsSubtarget &Subtarget) { 963 // ROOTNode must have a multiplication as an operand for the match to be 964 // successful. 965 if (ROOTNode->getOperand(0).getOpcode() != ISD::MUL && 966 ROOTNode->getOperand(1).getOpcode() != ISD::MUL) 967 return SDValue(); 968 969 // We don't handle vector types here. 970 if (ROOTNode->getValueType(0).isVector()) 971 return SDValue(); 972 973 // For MIPS64, madd / msub instructions are inefficent to use with 64 bit 974 // arithmetic. E.g. 975 // (add (mul a b) c) => 976 // let res = (madd (mthi (drotr c 32))x(mtlo c) a b) in 977 // MIPS64: (or (dsll (mfhi res) 32) (dsrl (dsll (mflo res) 32) 32) 978 // or 979 // MIPS64R2: (dins (mflo res) (mfhi res) 32 32) 980 // 981 // The overhead of setting up the Hi/Lo registers and reassembling the 982 // result makes this a dubious optimzation for MIPS64. The core of the 983 // problem is that Hi/Lo contain the upper and lower 32 bits of the 984 // operand and result. 985 // 986 // It requires a chain of 4 add/mul for MIPS64R2 to get better code 987 // density than doing it naively, 5 for MIPS64. Additionally, using 988 // madd/msub on MIPS64 requires the operands actually be 32 bit sign 989 // extended operands, not true 64 bit values. 990 // 991 // FIXME: For the moment, disable this completely for MIPS64. 992 if (Subtarget.hasMips64()) 993 return SDValue(); 994 995 SDValue Mult = ROOTNode->getOperand(0).getOpcode() == ISD::MUL 996 ? ROOTNode->getOperand(0) 997 : ROOTNode->getOperand(1); 998 999 SDValue AddOperand = ROOTNode->getOperand(0).getOpcode() == ISD::MUL 1000 ? ROOTNode->getOperand(1) 1001 : ROOTNode->getOperand(0); 1002 1003 // Transform this to a MADD only if the user of this node is the add. 1004 // If there are other users of the mul, this function returns here. 1005 if (!Mult.hasOneUse()) 1006 return SDValue(); 1007 1008 // maddu and madd are unusual instructions in that on MIPS64 bits 63..31 1009 // must be in canonical form, i.e. sign extended. For MIPS32, the operands 1010 // of the multiply must have 32 or more sign bits, otherwise we cannot 1011 // perform this optimization. We have to check this here as we're performing 1012 // this optimization pre-legalization. 1013 SDValue MultLHS = Mult->getOperand(0); 1014 SDValue MultRHS = Mult->getOperand(1); 1015 1016 bool IsSigned = MultLHS->getOpcode() == ISD::SIGN_EXTEND && 1017 MultRHS->getOpcode() == ISD::SIGN_EXTEND; 1018 bool IsUnsigned = MultLHS->getOpcode() == ISD::ZERO_EXTEND && 1019 MultRHS->getOpcode() == ISD::ZERO_EXTEND; 1020 1021 if (!IsSigned && !IsUnsigned) 1022 return SDValue(); 1023 1024 // Initialize accumulator. 1025 SDLoc DL(ROOTNode); 1026 SDValue TopHalf; 1027 SDValue BottomHalf; 1028 BottomHalf = CurDAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, AddOperand, 1029 CurDAG.getIntPtrConstant(0, DL)); 1030 1031 TopHalf = CurDAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, AddOperand, 1032 CurDAG.getIntPtrConstant(1, DL)); 1033 SDValue ACCIn = CurDAG.getNode(MipsISD::MTLOHI, DL, MVT::Untyped, 1034 BottomHalf, 1035 TopHalf); 1036 1037 // Create MipsMAdd(u) / MipsMSub(u) node. 1038 bool IsAdd = ROOTNode->getOpcode() == ISD::ADD; 1039 unsigned Opcode = IsAdd ? (IsUnsigned ? MipsISD::MAddu : MipsISD::MAdd) 1040 : (IsUnsigned ? MipsISD::MSubu : MipsISD::MSub); 1041 SDValue MAddOps[3] = { 1042 CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(0)), 1043 CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(1)), ACCIn}; 1044 EVT VTs[2] = {MVT::i32, MVT::i32}; 1045 SDValue MAdd = CurDAG.getNode(Opcode, DL, VTs, MAddOps); 1046 1047 SDValue ResLo = CurDAG.getNode(MipsISD::MFLO, DL, MVT::i32, MAdd); 1048 SDValue ResHi = CurDAG.getNode(MipsISD::MFHI, DL, MVT::i32, MAdd); 1049 SDValue Combined = 1050 CurDAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResLo, ResHi); 1051 return Combined; 1052 } 1053 1054 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG, 1055 TargetLowering::DAGCombinerInfo &DCI, 1056 const MipsSubtarget &Subtarget) { 1057 // (sub v0 (mul v1, v2)) => (msub v1, v2, v0) 1058 if (DCI.isBeforeLegalizeOps()) { 1059 if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() && 1060 !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64) 1061 return performMADD_MSUBCombine(N, DAG, Subtarget); 1062 1063 return SDValue(); 1064 } 1065 1066 return SDValue(); 1067 } 1068 1069 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 1070 TargetLowering::DAGCombinerInfo &DCI, 1071 const MipsSubtarget &Subtarget) { 1072 // (add v0 (mul v1, v2)) => (madd v1, v2, v0) 1073 if (DCI.isBeforeLegalizeOps()) { 1074 if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() && 1075 !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64) 1076 return performMADD_MSUBCombine(N, DAG, Subtarget); 1077 1078 return SDValue(); 1079 } 1080 1081 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt)) 1082 SDValue Add = N->getOperand(1); 1083 1084 if (Add.getOpcode() != ISD::ADD) 1085 return SDValue(); 1086 1087 SDValue Lo = Add.getOperand(1); 1088 1089 if ((Lo.getOpcode() != MipsISD::Lo) || 1090 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable)) 1091 return SDValue(); 1092 1093 EVT ValTy = N->getValueType(0); 1094 SDLoc DL(N); 1095 1096 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0), 1097 Add.getOperand(0)); 1098 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo); 1099 } 1100 1101 static SDValue performSHLCombine(SDNode *N, SelectionDAG &DAG, 1102 TargetLowering::DAGCombinerInfo &DCI, 1103 const MipsSubtarget &Subtarget) { 1104 // Pattern match CINS. 1105 // $dst = shl (and $src , imm), pos 1106 // => cins $dst, $src, pos, size 1107 1108 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasCnMips()) 1109 return SDValue(); 1110 1111 SDValue FirstOperand = N->getOperand(0); 1112 unsigned FirstOperandOpc = FirstOperand.getOpcode(); 1113 SDValue SecondOperand = N->getOperand(1); 1114 EVT ValTy = N->getValueType(0); 1115 SDLoc DL(N); 1116 1117 uint64_t Pos = 0, SMPos, SMSize; 1118 ConstantSDNode *CN; 1119 SDValue NewOperand; 1120 1121 // The second operand of the shift must be an immediate. 1122 if (!(CN = dyn_cast<ConstantSDNode>(SecondOperand))) 1123 return SDValue(); 1124 1125 Pos = CN->getZExtValue(); 1126 1127 if (Pos >= ValTy.getSizeInBits()) 1128 return SDValue(); 1129 1130 if (FirstOperandOpc != ISD::AND) 1131 return SDValue(); 1132 1133 // AND's second operand must be a shifted mask. 1134 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))) || 1135 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize)) 1136 return SDValue(); 1137 1138 // Return if the shifted mask does not start at bit 0 or the sum of its size 1139 // and Pos exceeds the word's size. 1140 if (SMPos != 0 || SMSize > 32 || Pos + SMSize > ValTy.getSizeInBits()) 1141 return SDValue(); 1142 1143 NewOperand = FirstOperand.getOperand(0); 1144 // SMSize is 'location' (position) in this case, not size. 1145 SMSize--; 1146 1147 return DAG.getNode(MipsISD::CIns, DL, ValTy, NewOperand, 1148 DAG.getConstant(Pos, DL, MVT::i32), 1149 DAG.getConstant(SMSize, DL, MVT::i32)); 1150 } 1151 1152 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) 1153 const { 1154 SelectionDAG &DAG = DCI.DAG; 1155 unsigned Opc = N->getOpcode(); 1156 1157 switch (Opc) { 1158 default: break; 1159 case ISD::SDIVREM: 1160 case ISD::UDIVREM: 1161 return performDivRemCombine(N, DAG, DCI, Subtarget); 1162 case ISD::SELECT: 1163 return performSELECTCombine(N, DAG, DCI, Subtarget); 1164 case MipsISD::CMovFP_F: 1165 case MipsISD::CMovFP_T: 1166 return performCMovFPCombine(N, DAG, DCI, Subtarget); 1167 case ISD::AND: 1168 return performANDCombine(N, DAG, DCI, Subtarget); 1169 case ISD::OR: 1170 return performORCombine(N, DAG, DCI, Subtarget); 1171 case ISD::ADD: 1172 return performADDCombine(N, DAG, DCI, Subtarget); 1173 case ISD::SHL: 1174 return performSHLCombine(N, DAG, DCI, Subtarget); 1175 case ISD::SUB: 1176 return performSUBCombine(N, DAG, DCI, Subtarget); 1177 } 1178 1179 return SDValue(); 1180 } 1181 1182 bool MipsTargetLowering::isCheapToSpeculateCttz() const { 1183 return Subtarget.hasMips32(); 1184 } 1185 1186 bool MipsTargetLowering::isCheapToSpeculateCtlz() const { 1187 return Subtarget.hasMips32(); 1188 } 1189 1190 bool MipsTargetLowering::shouldFoldConstantShiftPairToMask( 1191 const SDNode *N, CombineLevel Level) const { 1192 if (N->getOperand(0).getValueType().isVector()) 1193 return false; 1194 return true; 1195 } 1196 1197 void 1198 MipsTargetLowering::LowerOperationWrapper(SDNode *N, 1199 SmallVectorImpl<SDValue> &Results, 1200 SelectionDAG &DAG) const { 1201 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 1202 1203 if (Res) 1204 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I) 1205 Results.push_back(Res.getValue(I)); 1206 } 1207 1208 void 1209 MipsTargetLowering::ReplaceNodeResults(SDNode *N, 1210 SmallVectorImpl<SDValue> &Results, 1211 SelectionDAG &DAG) const { 1212 return LowerOperationWrapper(N, Results, DAG); 1213 } 1214 1215 SDValue MipsTargetLowering:: 1216 LowerOperation(SDValue Op, SelectionDAG &DAG) const 1217 { 1218 switch (Op.getOpcode()) 1219 { 1220 case ISD::BRCOND: return lowerBRCOND(Op, DAG); 1221 case ISD::ConstantPool: return lowerConstantPool(Op, DAG); 1222 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG); 1223 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG); 1224 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG); 1225 case ISD::JumpTable: return lowerJumpTable(Op, DAG); 1226 case ISD::SELECT: return lowerSELECT(Op, DAG); 1227 case ISD::SETCC: return lowerSETCC(Op, DAG); 1228 case ISD::VASTART: return lowerVASTART(Op, DAG); 1229 case ISD::VAARG: return lowerVAARG(Op, DAG); 1230 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG); 1231 case ISD::FABS: return lowerFABS(Op, DAG); 1232 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG); 1233 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG); 1234 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG); 1235 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG); 1236 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG); 1237 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true); 1238 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false); 1239 case ISD::LOAD: return lowerLOAD(Op, DAG); 1240 case ISD::STORE: return lowerSTORE(Op, DAG); 1241 case ISD::EH_DWARF_CFA: return lowerEH_DWARF_CFA(Op, DAG); 1242 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG); 1243 } 1244 return SDValue(); 1245 } 1246 1247 //===----------------------------------------------------------------------===// 1248 // Lower helper functions 1249 //===----------------------------------------------------------------------===// 1250 1251 // addLiveIn - This helper function adds the specified physical register to the 1252 // MachineFunction as a live in value. It also creates a corresponding 1253 // virtual register for it. 1254 static unsigned 1255 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC) 1256 { 1257 Register VReg = MF.getRegInfo().createVirtualRegister(RC); 1258 MF.getRegInfo().addLiveIn(PReg, VReg); 1259 return VReg; 1260 } 1261 1262 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr &MI, 1263 MachineBasicBlock &MBB, 1264 const TargetInstrInfo &TII, 1265 bool Is64Bit, bool IsMicroMips) { 1266 if (NoZeroDivCheck) 1267 return &MBB; 1268 1269 // Insert instruction "teq $divisor_reg, $zero, 7". 1270 MachineBasicBlock::iterator I(MI); 1271 MachineInstrBuilder MIB; 1272 MachineOperand &Divisor = MI.getOperand(2); 1273 MIB = BuildMI(MBB, std::next(I), MI.getDebugLoc(), 1274 TII.get(IsMicroMips ? Mips::TEQ_MM : Mips::TEQ)) 1275 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill())) 1276 .addReg(Mips::ZERO) 1277 .addImm(7); 1278 1279 // Use the 32-bit sub-register if this is a 64-bit division. 1280 if (Is64Bit) 1281 MIB->getOperand(0).setSubReg(Mips::sub_32); 1282 1283 // Clear Divisor's kill flag. 1284 Divisor.setIsKill(false); 1285 1286 // We would normally delete the original instruction here but in this case 1287 // we only needed to inject an additional instruction rather than replace it. 1288 1289 return &MBB; 1290 } 1291 1292 MachineBasicBlock * 1293 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 1294 MachineBasicBlock *BB) const { 1295 switch (MI.getOpcode()) { 1296 default: 1297 llvm_unreachable("Unexpected instr type to insert"); 1298 case Mips::ATOMIC_LOAD_ADD_I8: 1299 return emitAtomicBinaryPartword(MI, BB, 1); 1300 case Mips::ATOMIC_LOAD_ADD_I16: 1301 return emitAtomicBinaryPartword(MI, BB, 2); 1302 case Mips::ATOMIC_LOAD_ADD_I32: 1303 return emitAtomicBinary(MI, BB); 1304 case Mips::ATOMIC_LOAD_ADD_I64: 1305 return emitAtomicBinary(MI, BB); 1306 1307 case Mips::ATOMIC_LOAD_AND_I8: 1308 return emitAtomicBinaryPartword(MI, BB, 1); 1309 case Mips::ATOMIC_LOAD_AND_I16: 1310 return emitAtomicBinaryPartword(MI, BB, 2); 1311 case Mips::ATOMIC_LOAD_AND_I32: 1312 return emitAtomicBinary(MI, BB); 1313 case Mips::ATOMIC_LOAD_AND_I64: 1314 return emitAtomicBinary(MI, BB); 1315 1316 case Mips::ATOMIC_LOAD_OR_I8: 1317 return emitAtomicBinaryPartword(MI, BB, 1); 1318 case Mips::ATOMIC_LOAD_OR_I16: 1319 return emitAtomicBinaryPartword(MI, BB, 2); 1320 case Mips::ATOMIC_LOAD_OR_I32: 1321 return emitAtomicBinary(MI, BB); 1322 case Mips::ATOMIC_LOAD_OR_I64: 1323 return emitAtomicBinary(MI, BB); 1324 1325 case Mips::ATOMIC_LOAD_XOR_I8: 1326 return emitAtomicBinaryPartword(MI, BB, 1); 1327 case Mips::ATOMIC_LOAD_XOR_I16: 1328 return emitAtomicBinaryPartword(MI, BB, 2); 1329 case Mips::ATOMIC_LOAD_XOR_I32: 1330 return emitAtomicBinary(MI, BB); 1331 case Mips::ATOMIC_LOAD_XOR_I64: 1332 return emitAtomicBinary(MI, BB); 1333 1334 case Mips::ATOMIC_LOAD_NAND_I8: 1335 return emitAtomicBinaryPartword(MI, BB, 1); 1336 case Mips::ATOMIC_LOAD_NAND_I16: 1337 return emitAtomicBinaryPartword(MI, BB, 2); 1338 case Mips::ATOMIC_LOAD_NAND_I32: 1339 return emitAtomicBinary(MI, BB); 1340 case Mips::ATOMIC_LOAD_NAND_I64: 1341 return emitAtomicBinary(MI, BB); 1342 1343 case Mips::ATOMIC_LOAD_SUB_I8: 1344 return emitAtomicBinaryPartword(MI, BB, 1); 1345 case Mips::ATOMIC_LOAD_SUB_I16: 1346 return emitAtomicBinaryPartword(MI, BB, 2); 1347 case Mips::ATOMIC_LOAD_SUB_I32: 1348 return emitAtomicBinary(MI, BB); 1349 case Mips::ATOMIC_LOAD_SUB_I64: 1350 return emitAtomicBinary(MI, BB); 1351 1352 case Mips::ATOMIC_SWAP_I8: 1353 return emitAtomicBinaryPartword(MI, BB, 1); 1354 case Mips::ATOMIC_SWAP_I16: 1355 return emitAtomicBinaryPartword(MI, BB, 2); 1356 case Mips::ATOMIC_SWAP_I32: 1357 return emitAtomicBinary(MI, BB); 1358 case Mips::ATOMIC_SWAP_I64: 1359 return emitAtomicBinary(MI, BB); 1360 1361 case Mips::ATOMIC_CMP_SWAP_I8: 1362 return emitAtomicCmpSwapPartword(MI, BB, 1); 1363 case Mips::ATOMIC_CMP_SWAP_I16: 1364 return emitAtomicCmpSwapPartword(MI, BB, 2); 1365 case Mips::ATOMIC_CMP_SWAP_I32: 1366 return emitAtomicCmpSwap(MI, BB); 1367 case Mips::ATOMIC_CMP_SWAP_I64: 1368 return emitAtomicCmpSwap(MI, BB); 1369 case Mips::PseudoSDIV: 1370 case Mips::PseudoUDIV: 1371 case Mips::DIV: 1372 case Mips::DIVU: 1373 case Mips::MOD: 1374 case Mips::MODU: 1375 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false, 1376 false); 1377 case Mips::SDIV_MM_Pseudo: 1378 case Mips::UDIV_MM_Pseudo: 1379 case Mips::SDIV_MM: 1380 case Mips::UDIV_MM: 1381 case Mips::DIV_MMR6: 1382 case Mips::DIVU_MMR6: 1383 case Mips::MOD_MMR6: 1384 case Mips::MODU_MMR6: 1385 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false, true); 1386 case Mips::PseudoDSDIV: 1387 case Mips::PseudoDUDIV: 1388 case Mips::DDIV: 1389 case Mips::DDIVU: 1390 case Mips::DMOD: 1391 case Mips::DMODU: 1392 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true, false); 1393 1394 case Mips::PseudoSELECT_I: 1395 case Mips::PseudoSELECT_I64: 1396 case Mips::PseudoSELECT_S: 1397 case Mips::PseudoSELECT_D32: 1398 case Mips::PseudoSELECT_D64: 1399 return emitPseudoSELECT(MI, BB, false, Mips::BNE); 1400 case Mips::PseudoSELECTFP_F_I: 1401 case Mips::PseudoSELECTFP_F_I64: 1402 case Mips::PseudoSELECTFP_F_S: 1403 case Mips::PseudoSELECTFP_F_D32: 1404 case Mips::PseudoSELECTFP_F_D64: 1405 return emitPseudoSELECT(MI, BB, true, Mips::BC1F); 1406 case Mips::PseudoSELECTFP_T_I: 1407 case Mips::PseudoSELECTFP_T_I64: 1408 case Mips::PseudoSELECTFP_T_S: 1409 case Mips::PseudoSELECTFP_T_D32: 1410 case Mips::PseudoSELECTFP_T_D64: 1411 return emitPseudoSELECT(MI, BB, true, Mips::BC1T); 1412 case Mips::PseudoD_SELECT_I: 1413 case Mips::PseudoD_SELECT_I64: 1414 return emitPseudoD_SELECT(MI, BB); 1415 } 1416 } 1417 1418 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and 1419 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true) 1420 MachineBasicBlock * 1421 MipsTargetLowering::emitAtomicBinary(MachineInstr &MI, 1422 MachineBasicBlock *BB) const { 1423 1424 MachineFunction *MF = BB->getParent(); 1425 MachineRegisterInfo &RegInfo = MF->getRegInfo(); 1426 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 1427 DebugLoc DL = MI.getDebugLoc(); 1428 1429 unsigned AtomicOp; 1430 switch (MI.getOpcode()) { 1431 case Mips::ATOMIC_LOAD_ADD_I32: 1432 AtomicOp = Mips::ATOMIC_LOAD_ADD_I32_POSTRA; 1433 break; 1434 case Mips::ATOMIC_LOAD_SUB_I32: 1435 AtomicOp = Mips::ATOMIC_LOAD_SUB_I32_POSTRA; 1436 break; 1437 case Mips::ATOMIC_LOAD_AND_I32: 1438 AtomicOp = Mips::ATOMIC_LOAD_AND_I32_POSTRA; 1439 break; 1440 case Mips::ATOMIC_LOAD_OR_I32: 1441 AtomicOp = Mips::ATOMIC_LOAD_OR_I32_POSTRA; 1442 break; 1443 case Mips::ATOMIC_LOAD_XOR_I32: 1444 AtomicOp = Mips::ATOMIC_LOAD_XOR_I32_POSTRA; 1445 break; 1446 case Mips::ATOMIC_LOAD_NAND_I32: 1447 AtomicOp = Mips::ATOMIC_LOAD_NAND_I32_POSTRA; 1448 break; 1449 case Mips::ATOMIC_SWAP_I32: 1450 AtomicOp = Mips::ATOMIC_SWAP_I32_POSTRA; 1451 break; 1452 case Mips::ATOMIC_LOAD_ADD_I64: 1453 AtomicOp = Mips::ATOMIC_LOAD_ADD_I64_POSTRA; 1454 break; 1455 case Mips::ATOMIC_LOAD_SUB_I64: 1456 AtomicOp = Mips::ATOMIC_LOAD_SUB_I64_POSTRA; 1457 break; 1458 case Mips::ATOMIC_LOAD_AND_I64: 1459 AtomicOp = Mips::ATOMIC_LOAD_AND_I64_POSTRA; 1460 break; 1461 case Mips::ATOMIC_LOAD_OR_I64: 1462 AtomicOp = Mips::ATOMIC_LOAD_OR_I64_POSTRA; 1463 break; 1464 case Mips::ATOMIC_LOAD_XOR_I64: 1465 AtomicOp = Mips::ATOMIC_LOAD_XOR_I64_POSTRA; 1466 break; 1467 case Mips::ATOMIC_LOAD_NAND_I64: 1468 AtomicOp = Mips::ATOMIC_LOAD_NAND_I64_POSTRA; 1469 break; 1470 case Mips::ATOMIC_SWAP_I64: 1471 AtomicOp = Mips::ATOMIC_SWAP_I64_POSTRA; 1472 break; 1473 default: 1474 llvm_unreachable("Unknown pseudo atomic for replacement!"); 1475 } 1476 1477 Register OldVal = MI.getOperand(0).getReg(); 1478 Register Ptr = MI.getOperand(1).getReg(); 1479 Register Incr = MI.getOperand(2).getReg(); 1480 Register Scratch = RegInfo.createVirtualRegister(RegInfo.getRegClass(OldVal)); 1481 1482 MachineBasicBlock::iterator II(MI); 1483 1484 // The scratch registers here with the EarlyClobber | Define | Implicit 1485 // flags is used to persuade the register allocator and the machine 1486 // verifier to accept the usage of this register. This has to be a real 1487 // register which has an UNDEF value but is dead after the instruction which 1488 // is unique among the registers chosen for the instruction. 1489 1490 // The EarlyClobber flag has the semantic properties that the operand it is 1491 // attached to is clobbered before the rest of the inputs are read. Hence it 1492 // must be unique among the operands to the instruction. 1493 // The Define flag is needed to coerce the machine verifier that an Undef 1494 // value isn't a problem. 1495 // The Dead flag is needed as the value in scratch isn't used by any other 1496 // instruction. Kill isn't used as Dead is more precise. 1497 // The implicit flag is here due to the interaction between the other flags 1498 // and the machine verifier. 1499 1500 // For correctness purpose, a new pseudo is introduced here. We need this 1501 // new pseudo, so that FastRegisterAllocator does not see an ll/sc sequence 1502 // that is spread over >1 basic blocks. A register allocator which 1503 // introduces (or any codegen infact) a store, can violate the expectations 1504 // of the hardware. 1505 // 1506 // An atomic read-modify-write sequence starts with a linked load 1507 // instruction and ends with a store conditional instruction. The atomic 1508 // read-modify-write sequence fails if any of the following conditions 1509 // occur between the execution of ll and sc: 1510 // * A coherent store is completed by another process or coherent I/O 1511 // module into the block of synchronizable physical memory containing 1512 // the word. The size and alignment of the block is 1513 // implementation-dependent. 1514 // * A coherent store is executed between an LL and SC sequence on the 1515 // same processor to the block of synchornizable physical memory 1516 // containing the word. 1517 // 1518 1519 Register PtrCopy = RegInfo.createVirtualRegister(RegInfo.getRegClass(Ptr)); 1520 Register IncrCopy = RegInfo.createVirtualRegister(RegInfo.getRegClass(Incr)); 1521 1522 BuildMI(*BB, II, DL, TII->get(Mips::COPY), IncrCopy).addReg(Incr); 1523 BuildMI(*BB, II, DL, TII->get(Mips::COPY), PtrCopy).addReg(Ptr); 1524 1525 BuildMI(*BB, II, DL, TII->get(AtomicOp)) 1526 .addReg(OldVal, RegState::Define | RegState::EarlyClobber) 1527 .addReg(PtrCopy) 1528 .addReg(IncrCopy) 1529 .addReg(Scratch, RegState::Define | RegState::EarlyClobber | 1530 RegState::Implicit | RegState::Dead); 1531 1532 MI.eraseFromParent(); 1533 1534 return BB; 1535 } 1536 1537 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg( 1538 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg, 1539 unsigned SrcReg) const { 1540 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 1541 const DebugLoc &DL = MI.getDebugLoc(); 1542 1543 if (Subtarget.hasMips32r2() && Size == 1) { 1544 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg); 1545 return BB; 1546 } 1547 1548 if (Subtarget.hasMips32r2() && Size == 2) { 1549 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg); 1550 return BB; 1551 } 1552 1553 MachineFunction *MF = BB->getParent(); 1554 MachineRegisterInfo &RegInfo = MF->getRegInfo(); 1555 const TargetRegisterClass *RC = getRegClassFor(MVT::i32); 1556 Register ScrReg = RegInfo.createVirtualRegister(RC); 1557 1558 assert(Size < 32); 1559 int64_t ShiftImm = 32 - (Size * 8); 1560 1561 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm); 1562 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm); 1563 1564 return BB; 1565 } 1566 1567 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword( 1568 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const { 1569 assert((Size == 1 || Size == 2) && 1570 "Unsupported size for EmitAtomicBinaryPartial."); 1571 1572 MachineFunction *MF = BB->getParent(); 1573 MachineRegisterInfo &RegInfo = MF->getRegInfo(); 1574 const TargetRegisterClass *RC = getRegClassFor(MVT::i32); 1575 const bool ArePtrs64bit = ABI.ArePtrs64bit(); 1576 const TargetRegisterClass *RCp = 1577 getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32); 1578 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 1579 DebugLoc DL = MI.getDebugLoc(); 1580 1581 Register Dest = MI.getOperand(0).getReg(); 1582 Register Ptr = MI.getOperand(1).getReg(); 1583 Register Incr = MI.getOperand(2).getReg(); 1584 1585 Register AlignedAddr = RegInfo.createVirtualRegister(RCp); 1586 Register ShiftAmt = RegInfo.createVirtualRegister(RC); 1587 Register Mask = RegInfo.createVirtualRegister(RC); 1588 Register Mask2 = RegInfo.createVirtualRegister(RC); 1589 Register Incr2 = RegInfo.createVirtualRegister(RC); 1590 Register MaskLSB2 = RegInfo.createVirtualRegister(RCp); 1591 Register PtrLSB2 = RegInfo.createVirtualRegister(RC); 1592 Register MaskUpper = RegInfo.createVirtualRegister(RC); 1593 Register Scratch = RegInfo.createVirtualRegister(RC); 1594 Register Scratch2 = RegInfo.createVirtualRegister(RC); 1595 Register Scratch3 = RegInfo.createVirtualRegister(RC); 1596 1597 unsigned AtomicOp = 0; 1598 switch (MI.getOpcode()) { 1599 case Mips::ATOMIC_LOAD_NAND_I8: 1600 AtomicOp = Mips::ATOMIC_LOAD_NAND_I8_POSTRA; 1601 break; 1602 case Mips::ATOMIC_LOAD_NAND_I16: 1603 AtomicOp = Mips::ATOMIC_LOAD_NAND_I16_POSTRA; 1604 break; 1605 case Mips::ATOMIC_SWAP_I8: 1606 AtomicOp = Mips::ATOMIC_SWAP_I8_POSTRA; 1607 break; 1608 case Mips::ATOMIC_SWAP_I16: 1609 AtomicOp = Mips::ATOMIC_SWAP_I16_POSTRA; 1610 break; 1611 case Mips::ATOMIC_LOAD_ADD_I8: 1612 AtomicOp = Mips::ATOMIC_LOAD_ADD_I8_POSTRA; 1613 break; 1614 case Mips::ATOMIC_LOAD_ADD_I16: 1615 AtomicOp = Mips::ATOMIC_LOAD_ADD_I16_POSTRA; 1616 break; 1617 case Mips::ATOMIC_LOAD_SUB_I8: 1618 AtomicOp = Mips::ATOMIC_LOAD_SUB_I8_POSTRA; 1619 break; 1620 case Mips::ATOMIC_LOAD_SUB_I16: 1621 AtomicOp = Mips::ATOMIC_LOAD_SUB_I16_POSTRA; 1622 break; 1623 case Mips::ATOMIC_LOAD_AND_I8: 1624 AtomicOp = Mips::ATOMIC_LOAD_AND_I8_POSTRA; 1625 break; 1626 case Mips::ATOMIC_LOAD_AND_I16: 1627 AtomicOp = Mips::ATOMIC_LOAD_AND_I16_POSTRA; 1628 break; 1629 case Mips::ATOMIC_LOAD_OR_I8: 1630 AtomicOp = Mips::ATOMIC_LOAD_OR_I8_POSTRA; 1631 break; 1632 case Mips::ATOMIC_LOAD_OR_I16: 1633 AtomicOp = Mips::ATOMIC_LOAD_OR_I16_POSTRA; 1634 break; 1635 case Mips::ATOMIC_LOAD_XOR_I8: 1636 AtomicOp = Mips::ATOMIC_LOAD_XOR_I8_POSTRA; 1637 break; 1638 case Mips::ATOMIC_LOAD_XOR_I16: 1639 AtomicOp = Mips::ATOMIC_LOAD_XOR_I16_POSTRA; 1640 break; 1641 default: 1642 llvm_unreachable("Unknown subword atomic pseudo for expansion!"); 1643 } 1644 1645 // insert new blocks after the current block 1646 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 1647 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 1648 MachineFunction::iterator It = ++BB->getIterator(); 1649 MF->insert(It, exitMBB); 1650 1651 // Transfer the remainder of BB and its successor edges to exitMBB. 1652 exitMBB->splice(exitMBB->begin(), BB, 1653 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 1654 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 1655 1656 BB->addSuccessor(exitMBB, BranchProbability::getOne()); 1657 1658 // thisMBB: 1659 // addiu masklsb2,$0,-4 # 0xfffffffc 1660 // and alignedaddr,ptr,masklsb2 1661 // andi ptrlsb2,ptr,3 1662 // sll shiftamt,ptrlsb2,3 1663 // ori maskupper,$0,255 # 0xff 1664 // sll mask,maskupper,shiftamt 1665 // nor mask2,$0,mask 1666 // sll incr2,incr,shiftamt 1667 1668 int64_t MaskImm = (Size == 1) ? 255 : 65535; 1669 BuildMI(BB, DL, TII->get(ABI.GetPtrAddiuOp()), MaskLSB2) 1670 .addReg(ABI.GetNullPtr()).addImm(-4); 1671 BuildMI(BB, DL, TII->get(ABI.GetPtrAndOp()), AlignedAddr) 1672 .addReg(Ptr).addReg(MaskLSB2); 1673 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2) 1674 .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3); 1675 if (Subtarget.isLittle()) { 1676 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3); 1677 } else { 1678 Register Off = RegInfo.createVirtualRegister(RC); 1679 BuildMI(BB, DL, TII->get(Mips::XORi), Off) 1680 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2); 1681 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3); 1682 } 1683 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper) 1684 .addReg(Mips::ZERO).addImm(MaskImm); 1685 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask) 1686 .addReg(MaskUpper).addReg(ShiftAmt); 1687 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask); 1688 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt); 1689 1690 1691 // The purposes of the flags on the scratch registers is explained in 1692 // emitAtomicBinary. In summary, we need a scratch register which is going to 1693 // be undef, that is unique among registers chosen for the instruction. 1694 1695 BuildMI(BB, DL, TII->get(AtomicOp)) 1696 .addReg(Dest, RegState::Define | RegState::EarlyClobber) 1697 .addReg(AlignedAddr) 1698 .addReg(Incr2) 1699 .addReg(Mask) 1700 .addReg(Mask2) 1701 .addReg(ShiftAmt) 1702 .addReg(Scratch, RegState::EarlyClobber | RegState::Define | 1703 RegState::Dead | RegState::Implicit) 1704 .addReg(Scratch2, RegState::EarlyClobber | RegState::Define | 1705 RegState::Dead | RegState::Implicit) 1706 .addReg(Scratch3, RegState::EarlyClobber | RegState::Define | 1707 RegState::Dead | RegState::Implicit); 1708 1709 MI.eraseFromParent(); // The instruction is gone now. 1710 1711 return exitMBB; 1712 } 1713 1714 // Lower atomic compare and swap to a pseudo instruction, taking care to 1715 // define a scratch register for the pseudo instruction's expansion. The 1716 // instruction is expanded after the register allocator as to prevent 1717 // the insertion of stores between the linked load and the store conditional. 1718 1719 MachineBasicBlock * 1720 MipsTargetLowering::emitAtomicCmpSwap(MachineInstr &MI, 1721 MachineBasicBlock *BB) const { 1722 1723 assert((MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 || 1724 MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I64) && 1725 "Unsupported atomic pseudo for EmitAtomicCmpSwap."); 1726 1727 const unsigned Size = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 ? 4 : 8; 1728 1729 MachineFunction *MF = BB->getParent(); 1730 MachineRegisterInfo &MRI = MF->getRegInfo(); 1731 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8)); 1732 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 1733 DebugLoc DL = MI.getDebugLoc(); 1734 1735 unsigned AtomicOp = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 1736 ? Mips::ATOMIC_CMP_SWAP_I32_POSTRA 1737 : Mips::ATOMIC_CMP_SWAP_I64_POSTRA; 1738 Register Dest = MI.getOperand(0).getReg(); 1739 Register Ptr = MI.getOperand(1).getReg(); 1740 Register OldVal = MI.getOperand(2).getReg(); 1741 Register NewVal = MI.getOperand(3).getReg(); 1742 1743 Register Scratch = MRI.createVirtualRegister(RC); 1744 MachineBasicBlock::iterator II(MI); 1745 1746 // We need to create copies of the various registers and kill them at the 1747 // atomic pseudo. If the copies are not made, when the atomic is expanded 1748 // after fast register allocation, the spills will end up outside of the 1749 // blocks that their values are defined in, causing livein errors. 1750 1751 Register PtrCopy = MRI.createVirtualRegister(MRI.getRegClass(Ptr)); 1752 Register OldValCopy = MRI.createVirtualRegister(MRI.getRegClass(OldVal)); 1753 Register NewValCopy = MRI.createVirtualRegister(MRI.getRegClass(NewVal)); 1754 1755 BuildMI(*BB, II, DL, TII->get(Mips::COPY), PtrCopy).addReg(Ptr); 1756 BuildMI(*BB, II, DL, TII->get(Mips::COPY), OldValCopy).addReg(OldVal); 1757 BuildMI(*BB, II, DL, TII->get(Mips::COPY), NewValCopy).addReg(NewVal); 1758 1759 // The purposes of the flags on the scratch registers is explained in 1760 // emitAtomicBinary. In summary, we need a scratch register which is going to 1761 // be undef, that is unique among registers chosen for the instruction. 1762 1763 BuildMI(*BB, II, DL, TII->get(AtomicOp)) 1764 .addReg(Dest, RegState::Define | RegState::EarlyClobber) 1765 .addReg(PtrCopy, RegState::Kill) 1766 .addReg(OldValCopy, RegState::Kill) 1767 .addReg(NewValCopy, RegState::Kill) 1768 .addReg(Scratch, RegState::EarlyClobber | RegState::Define | 1769 RegState::Dead | RegState::Implicit); 1770 1771 MI.eraseFromParent(); // The instruction is gone now. 1772 1773 return BB; 1774 } 1775 1776 MachineBasicBlock *MipsTargetLowering::emitAtomicCmpSwapPartword( 1777 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const { 1778 assert((Size == 1 || Size == 2) && 1779 "Unsupported size for EmitAtomicCmpSwapPartial."); 1780 1781 MachineFunction *MF = BB->getParent(); 1782 MachineRegisterInfo &RegInfo = MF->getRegInfo(); 1783 const TargetRegisterClass *RC = getRegClassFor(MVT::i32); 1784 const bool ArePtrs64bit = ABI.ArePtrs64bit(); 1785 const TargetRegisterClass *RCp = 1786 getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32); 1787 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 1788 DebugLoc DL = MI.getDebugLoc(); 1789 1790 Register Dest = MI.getOperand(0).getReg(); 1791 Register Ptr = MI.getOperand(1).getReg(); 1792 Register CmpVal = MI.getOperand(2).getReg(); 1793 Register NewVal = MI.getOperand(3).getReg(); 1794 1795 Register AlignedAddr = RegInfo.createVirtualRegister(RCp); 1796 Register ShiftAmt = RegInfo.createVirtualRegister(RC); 1797 Register Mask = RegInfo.createVirtualRegister(RC); 1798 Register Mask2 = RegInfo.createVirtualRegister(RC); 1799 Register ShiftedCmpVal = RegInfo.createVirtualRegister(RC); 1800 Register ShiftedNewVal = RegInfo.createVirtualRegister(RC); 1801 Register MaskLSB2 = RegInfo.createVirtualRegister(RCp); 1802 Register PtrLSB2 = RegInfo.createVirtualRegister(RC); 1803 Register MaskUpper = RegInfo.createVirtualRegister(RC); 1804 Register MaskedCmpVal = RegInfo.createVirtualRegister(RC); 1805 Register MaskedNewVal = RegInfo.createVirtualRegister(RC); 1806 unsigned AtomicOp = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I8 1807 ? Mips::ATOMIC_CMP_SWAP_I8_POSTRA 1808 : Mips::ATOMIC_CMP_SWAP_I16_POSTRA; 1809 1810 // The scratch registers here with the EarlyClobber | Define | Dead | Implicit 1811 // flags are used to coerce the register allocator and the machine verifier to 1812 // accept the usage of these registers. 1813 // The EarlyClobber flag has the semantic properties that the operand it is 1814 // attached to is clobbered before the rest of the inputs are read. Hence it 1815 // must be unique among the operands to the instruction. 1816 // The Define flag is needed to coerce the machine verifier that an Undef 1817 // value isn't a problem. 1818 // The Dead flag is needed as the value in scratch isn't used by any other 1819 // instruction. Kill isn't used as Dead is more precise. 1820 Register Scratch = RegInfo.createVirtualRegister(RC); 1821 Register Scratch2 = RegInfo.createVirtualRegister(RC); 1822 1823 // insert new blocks after the current block 1824 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 1825 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 1826 MachineFunction::iterator It = ++BB->getIterator(); 1827 MF->insert(It, exitMBB); 1828 1829 // Transfer the remainder of BB and its successor edges to exitMBB. 1830 exitMBB->splice(exitMBB->begin(), BB, 1831 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 1832 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 1833 1834 BB->addSuccessor(exitMBB, BranchProbability::getOne()); 1835 1836 // thisMBB: 1837 // addiu masklsb2,$0,-4 # 0xfffffffc 1838 // and alignedaddr,ptr,masklsb2 1839 // andi ptrlsb2,ptr,3 1840 // xori ptrlsb2,ptrlsb2,3 # Only for BE 1841 // sll shiftamt,ptrlsb2,3 1842 // ori maskupper,$0,255 # 0xff 1843 // sll mask,maskupper,shiftamt 1844 // nor mask2,$0,mask 1845 // andi maskedcmpval,cmpval,255 1846 // sll shiftedcmpval,maskedcmpval,shiftamt 1847 // andi maskednewval,newval,255 1848 // sll shiftednewval,maskednewval,shiftamt 1849 int64_t MaskImm = (Size == 1) ? 255 : 65535; 1850 BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::DADDiu : Mips::ADDiu), MaskLSB2) 1851 .addReg(ABI.GetNullPtr()).addImm(-4); 1852 BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::AND64 : Mips::AND), AlignedAddr) 1853 .addReg(Ptr).addReg(MaskLSB2); 1854 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2) 1855 .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3); 1856 if (Subtarget.isLittle()) { 1857 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3); 1858 } else { 1859 Register Off = RegInfo.createVirtualRegister(RC); 1860 BuildMI(BB, DL, TII->get(Mips::XORi), Off) 1861 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2); 1862 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3); 1863 } 1864 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper) 1865 .addReg(Mips::ZERO).addImm(MaskImm); 1866 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask) 1867 .addReg(MaskUpper).addReg(ShiftAmt); 1868 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask); 1869 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal) 1870 .addReg(CmpVal).addImm(MaskImm); 1871 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal) 1872 .addReg(MaskedCmpVal).addReg(ShiftAmt); 1873 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal) 1874 .addReg(NewVal).addImm(MaskImm); 1875 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal) 1876 .addReg(MaskedNewVal).addReg(ShiftAmt); 1877 1878 // The purposes of the flags on the scratch registers are explained in 1879 // emitAtomicBinary. In summary, we need a scratch register which is going to 1880 // be undef, that is unique among the register chosen for the instruction. 1881 1882 BuildMI(BB, DL, TII->get(AtomicOp)) 1883 .addReg(Dest, RegState::Define | RegState::EarlyClobber) 1884 .addReg(AlignedAddr) 1885 .addReg(Mask) 1886 .addReg(ShiftedCmpVal) 1887 .addReg(Mask2) 1888 .addReg(ShiftedNewVal) 1889 .addReg(ShiftAmt) 1890 .addReg(Scratch, RegState::EarlyClobber | RegState::Define | 1891 RegState::Dead | RegState::Implicit) 1892 .addReg(Scratch2, RegState::EarlyClobber | RegState::Define | 1893 RegState::Dead | RegState::Implicit); 1894 1895 MI.eraseFromParent(); // The instruction is gone now. 1896 1897 return exitMBB; 1898 } 1899 1900 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 1901 // The first operand is the chain, the second is the condition, the third is 1902 // the block to branch to if the condition is true. 1903 SDValue Chain = Op.getOperand(0); 1904 SDValue Dest = Op.getOperand(2); 1905 SDLoc DL(Op); 1906 1907 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6()); 1908 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1)); 1909 1910 // Return if flag is not set by a floating point comparison. 1911 if (CondRes.getOpcode() != MipsISD::FPCmp) 1912 return Op; 1913 1914 SDValue CCNode = CondRes.getOperand(2); 1915 Mips::CondCode CC = 1916 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue(); 1917 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T; 1918 SDValue BrCode = DAG.getConstant(Opc, DL, MVT::i32); 1919 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32); 1920 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode, 1921 FCC0, Dest, CondRes); 1922 } 1923 1924 SDValue MipsTargetLowering:: 1925 lowerSELECT(SDValue Op, SelectionDAG &DAG) const 1926 { 1927 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6()); 1928 SDValue Cond = createFPCmp(DAG, Op.getOperand(0)); 1929 1930 // Return if flag is not set by a floating point comparison. 1931 if (Cond.getOpcode() != MipsISD::FPCmp) 1932 return Op; 1933 1934 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2), 1935 SDLoc(Op)); 1936 } 1937 1938 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const { 1939 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6()); 1940 SDValue Cond = createFPCmp(DAG, Op); 1941 1942 assert(Cond.getOpcode() == MipsISD::FPCmp && 1943 "Floating point operand expected."); 1944 1945 SDLoc DL(Op); 1946 SDValue True = DAG.getConstant(1, DL, MVT::i32); 1947 SDValue False = DAG.getConstant(0, DL, MVT::i32); 1948 1949 return createCMovFP(DAG, Cond, True, False, DL); 1950 } 1951 1952 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op, 1953 SelectionDAG &DAG) const { 1954 EVT Ty = Op.getValueType(); 1955 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 1956 const GlobalValue *GV = N->getGlobal(); 1957 1958 if (!isPositionIndependent()) { 1959 const MipsTargetObjectFile *TLOF = 1960 static_cast<const MipsTargetObjectFile *>( 1961 getTargetMachine().getObjFileLowering()); 1962 const GlobalObject *GO = GV->getBaseObject(); 1963 if (GO && TLOF->IsGlobalInSmallSection(GO, getTargetMachine())) 1964 // %gp_rel relocation 1965 return getAddrGPRel(N, SDLoc(N), Ty, DAG, ABI.IsN64()); 1966 1967 // %hi/%lo relocation 1968 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG) 1969 // %highest/%higher/%hi/%lo relocation 1970 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG); 1971 } 1972 1973 // Every other architecture would use shouldAssumeDSOLocal in here, but 1974 // mips is special. 1975 // * In PIC code mips requires got loads even for local statics! 1976 // * To save on got entries, for local statics the got entry contains the 1977 // page and an additional add instruction takes care of the low bits. 1978 // * It is legal to access a hidden symbol with a non hidden undefined, 1979 // so one cannot guarantee that all access to a hidden symbol will know 1980 // it is hidden. 1981 // * Mips linkers don't support creating a page and a full got entry for 1982 // the same symbol. 1983 // * Given all that, we have to use a full got entry for hidden symbols :-( 1984 if (GV->hasLocalLinkage()) 1985 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64()); 1986 1987 if (Subtarget.useXGOT()) 1988 return getAddrGlobalLargeGOT( 1989 N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16, MipsII::MO_GOT_LO16, 1990 DAG.getEntryNode(), 1991 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 1992 1993 return getAddrGlobal( 1994 N, SDLoc(N), Ty, DAG, 1995 (ABI.IsN32() || ABI.IsN64()) ? MipsII::MO_GOT_DISP : MipsII::MO_GOT, 1996 DAG.getEntryNode(), MachinePointerInfo::getGOT(DAG.getMachineFunction())); 1997 } 1998 1999 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op, 2000 SelectionDAG &DAG) const { 2001 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 2002 EVT Ty = Op.getValueType(); 2003 2004 if (!isPositionIndependent()) 2005 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG) 2006 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG); 2007 2008 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64()); 2009 } 2010 2011 SDValue MipsTargetLowering:: 2012 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const 2013 { 2014 // If the relocation model is PIC, use the General Dynamic TLS Model or 2015 // Local Dynamic TLS model, otherwise use the Initial Exec or 2016 // Local Exec TLS Model. 2017 2018 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2019 if (DAG.getTarget().useEmulatedTLS()) 2020 return LowerToTLSEmulatedModel(GA, DAG); 2021 2022 SDLoc DL(GA); 2023 const GlobalValue *GV = GA->getGlobal(); 2024 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2025 2026 TLSModel::Model model = getTargetMachine().getTLSModel(GV); 2027 2028 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) { 2029 // General Dynamic and Local Dynamic TLS Model. 2030 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM 2031 : MipsII::MO_TLSGD; 2032 2033 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag); 2034 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, 2035 getGlobalReg(DAG, PtrVT), TGA); 2036 unsigned PtrSize = PtrVT.getSizeInBits(); 2037 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize); 2038 2039 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT); 2040 2041 ArgListTy Args; 2042 ArgListEntry Entry; 2043 Entry.Node = Argument; 2044 Entry.Ty = PtrTy; 2045 Args.push_back(Entry); 2046 2047 TargetLowering::CallLoweringInfo CLI(DAG); 2048 CLI.setDebugLoc(DL) 2049 .setChain(DAG.getEntryNode()) 2050 .setLibCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args)); 2051 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2052 2053 SDValue Ret = CallResult.first; 2054 2055 if (model != TLSModel::LocalDynamic) 2056 return Ret; 2057 2058 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 2059 MipsII::MO_DTPREL_HI); 2060 SDValue Hi = DAG.getNode(MipsISD::TlsHi, DL, PtrVT, TGAHi); 2061 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 2062 MipsII::MO_DTPREL_LO); 2063 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo); 2064 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret); 2065 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo); 2066 } 2067 2068 SDValue Offset; 2069 if (model == TLSModel::InitialExec) { 2070 // Initial Exec TLS Model 2071 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 2072 MipsII::MO_GOTTPREL); 2073 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT), 2074 TGA); 2075 Offset = 2076 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), TGA, MachinePointerInfo()); 2077 } else { 2078 // Local Exec TLS Model 2079 assert(model == TLSModel::LocalExec); 2080 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 2081 MipsII::MO_TPREL_HI); 2082 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 2083 MipsII::MO_TPREL_LO); 2084 SDValue Hi = DAG.getNode(MipsISD::TlsHi, DL, PtrVT, TGAHi); 2085 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo); 2086 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2087 } 2088 2089 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT); 2090 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset); 2091 } 2092 2093 SDValue MipsTargetLowering:: 2094 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const 2095 { 2096 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 2097 EVT Ty = Op.getValueType(); 2098 2099 if (!isPositionIndependent()) 2100 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG) 2101 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG); 2102 2103 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64()); 2104 } 2105 2106 SDValue MipsTargetLowering:: 2107 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const 2108 { 2109 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 2110 EVT Ty = Op.getValueType(); 2111 2112 if (!isPositionIndependent()) { 2113 const MipsTargetObjectFile *TLOF = 2114 static_cast<const MipsTargetObjectFile *>( 2115 getTargetMachine().getObjFileLowering()); 2116 2117 if (TLOF->IsConstantInSmallSection(DAG.getDataLayout(), N->getConstVal(), 2118 getTargetMachine())) 2119 // %gp_rel relocation 2120 return getAddrGPRel(N, SDLoc(N), Ty, DAG, ABI.IsN64()); 2121 2122 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG) 2123 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG); 2124 } 2125 2126 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64()); 2127 } 2128 2129 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 2130 MachineFunction &MF = DAG.getMachineFunction(); 2131 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>(); 2132 2133 SDLoc DL(Op); 2134 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 2135 getPointerTy(MF.getDataLayout())); 2136 2137 // vastart just stores the address of the VarArgsFrameIndex slot into the 2138 // memory location argument. 2139 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2140 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 2141 MachinePointerInfo(SV)); 2142 } 2143 2144 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const { 2145 SDNode *Node = Op.getNode(); 2146 EVT VT = Node->getValueType(0); 2147 SDValue Chain = Node->getOperand(0); 2148 SDValue VAListPtr = Node->getOperand(1); 2149 const Align Align = 2150 llvm::MaybeAlign(Node->getConstantOperandVal(3)).valueOrOne(); 2151 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2152 SDLoc DL(Node); 2153 unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4; 2154 2155 SDValue VAListLoad = DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL, Chain, 2156 VAListPtr, MachinePointerInfo(SV)); 2157 SDValue VAList = VAListLoad; 2158 2159 // Re-align the pointer if necessary. 2160 // It should only ever be necessary for 64-bit types on O32 since the minimum 2161 // argument alignment is the same as the maximum type alignment for N32/N64. 2162 // 2163 // FIXME: We currently align too often. The code generator doesn't notice 2164 // when the pointer is still aligned from the last va_arg (or pair of 2165 // va_args for the i64 on O32 case). 2166 if (Align > getMinStackArgumentAlignment()) { 2167 VAList = DAG.getNode( 2168 ISD::ADD, DL, VAList.getValueType(), VAList, 2169 DAG.getConstant(Align.value() - 1, DL, VAList.getValueType())); 2170 2171 VAList = DAG.getNode( 2172 ISD::AND, DL, VAList.getValueType(), VAList, 2173 DAG.getConstant(-(int64_t)Align.value(), DL, VAList.getValueType())); 2174 } 2175 2176 // Increment the pointer, VAList, to the next vaarg. 2177 auto &TD = DAG.getDataLayout(); 2178 unsigned ArgSizeInBytes = 2179 TD.getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext())); 2180 SDValue Tmp3 = 2181 DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList, 2182 DAG.getConstant(alignTo(ArgSizeInBytes, ArgSlotSizeInBytes), 2183 DL, VAList.getValueType())); 2184 // Store the incremented VAList to the legalized pointer 2185 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr, 2186 MachinePointerInfo(SV)); 2187 2188 // In big-endian mode we must adjust the pointer when the load size is smaller 2189 // than the argument slot size. We must also reduce the known alignment to 2190 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get 2191 // the correct half of the slot, and reduce the alignment from 8 (slot 2192 // alignment) down to 4 (type alignment). 2193 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) { 2194 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes; 2195 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList, 2196 DAG.getIntPtrConstant(Adjustment, DL)); 2197 } 2198 // Load the actual argument out of the pointer VAList 2199 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo()); 2200 } 2201 2202 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, 2203 bool HasExtractInsert) { 2204 EVT TyX = Op.getOperand(0).getValueType(); 2205 EVT TyY = Op.getOperand(1).getValueType(); 2206 SDLoc DL(Op); 2207 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32); 2208 SDValue Const31 = DAG.getConstant(31, DL, MVT::i32); 2209 SDValue Res; 2210 2211 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it 2212 // to i32. 2213 SDValue X = (TyX == MVT::f32) ? 2214 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) : 2215 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0), 2216 Const1); 2217 SDValue Y = (TyY == MVT::f32) ? 2218 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) : 2219 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1), 2220 Const1); 2221 2222 if (HasExtractInsert) { 2223 // ext E, Y, 31, 1 ; extract bit31 of Y 2224 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X 2225 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1); 2226 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X); 2227 } else { 2228 // sll SllX, X, 1 2229 // srl SrlX, SllX, 1 2230 // srl SrlY, Y, 31 2231 // sll SllY, SrlX, 31 2232 // or Or, SrlX, SllY 2233 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1); 2234 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1); 2235 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31); 2236 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31); 2237 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY); 2238 } 2239 2240 if (TyX == MVT::f32) 2241 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res); 2242 2243 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, 2244 Op.getOperand(0), 2245 DAG.getConstant(0, DL, MVT::i32)); 2246 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res); 2247 } 2248 2249 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, 2250 bool HasExtractInsert) { 2251 unsigned WidthX = Op.getOperand(0).getValueSizeInBits(); 2252 unsigned WidthY = Op.getOperand(1).getValueSizeInBits(); 2253 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY); 2254 SDLoc DL(Op); 2255 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32); 2256 2257 // Bitcast to integer nodes. 2258 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0)); 2259 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1)); 2260 2261 if (HasExtractInsert) { 2262 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y 2263 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X 2264 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y, 2265 DAG.getConstant(WidthY - 1, DL, MVT::i32), Const1); 2266 2267 if (WidthX > WidthY) 2268 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E); 2269 else if (WidthY > WidthX) 2270 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E); 2271 2272 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E, 2273 DAG.getConstant(WidthX - 1, DL, MVT::i32), Const1, 2274 X); 2275 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I); 2276 } 2277 2278 // (d)sll SllX, X, 1 2279 // (d)srl SrlX, SllX, 1 2280 // (d)srl SrlY, Y, width(Y)-1 2281 // (d)sll SllY, SrlX, width(Y)-1 2282 // or Or, SrlX, SllY 2283 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1); 2284 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1); 2285 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y, 2286 DAG.getConstant(WidthY - 1, DL, MVT::i32)); 2287 2288 if (WidthX > WidthY) 2289 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY); 2290 else if (WidthY > WidthX) 2291 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY); 2292 2293 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY, 2294 DAG.getConstant(WidthX - 1, DL, MVT::i32)); 2295 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY); 2296 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or); 2297 } 2298 2299 SDValue 2300 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 2301 if (Subtarget.isGP64bit()) 2302 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert()); 2303 2304 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert()); 2305 } 2306 2307 static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG, 2308 bool HasExtractInsert) { 2309 SDLoc DL(Op); 2310 SDValue Res, Const1 = DAG.getConstant(1, DL, MVT::i32); 2311 2312 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it 2313 // to i32. 2314 SDValue X = (Op.getValueType() == MVT::f32) 2315 ? DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) 2316 : DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, 2317 Op.getOperand(0), Const1); 2318 2319 // Clear MSB. 2320 if (HasExtractInsert) 2321 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, 2322 DAG.getRegister(Mips::ZERO, MVT::i32), 2323 DAG.getConstant(31, DL, MVT::i32), Const1, X); 2324 else { 2325 // TODO: Provide DAG patterns which transform (and x, cst) 2326 // back to a (shl (srl x (clz cst)) (clz cst)) sequence. 2327 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1); 2328 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1); 2329 } 2330 2331 if (Op.getValueType() == MVT::f32) 2332 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res); 2333 2334 // FIXME: For mips32r2, the sequence of (BuildPairF64 (ins (ExtractElementF64 2335 // Op 1), $zero, 31 1) (ExtractElementF64 Op 0)) and the Op has one use, we 2336 // should be able to drop the usage of mfc1/mtc1 and rewrite the register in 2337 // place. 2338 SDValue LowX = 2339 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0), 2340 DAG.getConstant(0, DL, MVT::i32)); 2341 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res); 2342 } 2343 2344 static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG, 2345 bool HasExtractInsert) { 2346 SDLoc DL(Op); 2347 SDValue Res, Const1 = DAG.getConstant(1, DL, MVT::i32); 2348 2349 // Bitcast to integer node. 2350 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0)); 2351 2352 // Clear MSB. 2353 if (HasExtractInsert) 2354 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64, 2355 DAG.getRegister(Mips::ZERO_64, MVT::i64), 2356 DAG.getConstant(63, DL, MVT::i32), Const1, X); 2357 else { 2358 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1); 2359 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1); 2360 } 2361 2362 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res); 2363 } 2364 2365 SDValue MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const { 2366 if ((ABI.IsN32() || ABI.IsN64()) && (Op.getValueType() == MVT::f64)) 2367 return lowerFABS64(Op, DAG, Subtarget.hasExtractInsert()); 2368 2369 return lowerFABS32(Op, DAG, Subtarget.hasExtractInsert()); 2370 } 2371 2372 SDValue MipsTargetLowering:: 2373 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 2374 // check the depth 2375 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) { 2376 DAG.getContext()->emitError( 2377 "return address can be determined only for current frame"); 2378 return SDValue(); 2379 } 2380 2381 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 2382 MFI.setFrameAddressIsTaken(true); 2383 EVT VT = Op.getValueType(); 2384 SDLoc DL(Op); 2385 SDValue FrameAddr = DAG.getCopyFromReg( 2386 DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT); 2387 return FrameAddr; 2388 } 2389 2390 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op, 2391 SelectionDAG &DAG) const { 2392 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 2393 return SDValue(); 2394 2395 // check the depth 2396 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) { 2397 DAG.getContext()->emitError( 2398 "return address can be determined only for current frame"); 2399 return SDValue(); 2400 } 2401 2402 MachineFunction &MF = DAG.getMachineFunction(); 2403 MachineFrameInfo &MFI = MF.getFrameInfo(); 2404 MVT VT = Op.getSimpleValueType(); 2405 unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA; 2406 MFI.setReturnAddressIsTaken(true); 2407 2408 // Return RA, which contains the return address. Mark it an implicit live-in. 2409 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT)); 2410 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT); 2411 } 2412 2413 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is 2414 // generated from __builtin_eh_return (offset, handler) 2415 // The effect of this is to adjust the stack pointer by "offset" 2416 // and then branch to "handler". 2417 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG) 2418 const { 2419 MachineFunction &MF = DAG.getMachineFunction(); 2420 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>(); 2421 2422 MipsFI->setCallsEhReturn(); 2423 SDValue Chain = Op.getOperand(0); 2424 SDValue Offset = Op.getOperand(1); 2425 SDValue Handler = Op.getOperand(2); 2426 SDLoc DL(Op); 2427 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32; 2428 2429 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and 2430 // EH_RETURN nodes, so that instructions are emitted back-to-back. 2431 unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1; 2432 unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0; 2433 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue()); 2434 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1)); 2435 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain, 2436 DAG.getRegister(OffsetReg, Ty), 2437 DAG.getRegister(AddrReg, getPointerTy(MF.getDataLayout())), 2438 Chain.getValue(1)); 2439 } 2440 2441 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op, 2442 SelectionDAG &DAG) const { 2443 // FIXME: Need pseudo-fence for 'singlethread' fences 2444 // FIXME: Set SType for weaker fences where supported/appropriate. 2445 unsigned SType = 0; 2446 SDLoc DL(Op); 2447 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0), 2448 DAG.getConstant(SType, DL, MVT::i32)); 2449 } 2450 2451 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op, 2452 SelectionDAG &DAG) const { 2453 SDLoc DL(Op); 2454 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32; 2455 2456 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1); 2457 SDValue Shamt = Op.getOperand(2); 2458 // if shamt < (VT.bits): 2459 // lo = (shl lo, shamt) 2460 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt)) 2461 // else: 2462 // lo = 0 2463 // hi = (shl lo, shamt[4:0]) 2464 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt, 2465 DAG.getConstant(-1, DL, MVT::i32)); 2466 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, 2467 DAG.getConstant(1, DL, VT)); 2468 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not); 2469 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 2470 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 2471 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 2472 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt, 2473 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32)); 2474 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, 2475 DAG.getConstant(0, DL, VT), ShiftLeftLo); 2476 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or); 2477 2478 SDValue Ops[2] = {Lo, Hi}; 2479 return DAG.getMergeValues(Ops, DL); 2480 } 2481 2482 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 2483 bool IsSRA) const { 2484 SDLoc DL(Op); 2485 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1); 2486 SDValue Shamt = Op.getOperand(2); 2487 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32; 2488 2489 // if shamt < (VT.bits): 2490 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt)) 2491 // if isSRA: 2492 // hi = (sra hi, shamt) 2493 // else: 2494 // hi = (srl hi, shamt) 2495 // else: 2496 // if isSRA: 2497 // lo = (sra hi, shamt[4:0]) 2498 // hi = (sra hi, 31) 2499 // else: 2500 // lo = (srl hi, shamt[4:0]) 2501 // hi = 0 2502 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt, 2503 DAG.getConstant(-1, DL, MVT::i32)); 2504 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi, 2505 DAG.getConstant(1, DL, VT)); 2506 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not); 2507 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 2508 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 2509 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, 2510 DL, VT, Hi, Shamt); 2511 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt, 2512 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32)); 2513 SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi, 2514 DAG.getConstant(VT.getSizeInBits() - 1, DL, VT)); 2515 2516 if (!(Subtarget.hasMips4() || Subtarget.hasMips32())) { 2517 SDVTList VTList = DAG.getVTList(VT, VT); 2518 return DAG.getNode(Subtarget.isGP64bit() ? Mips::PseudoD_SELECT_I64 2519 : Mips::PseudoD_SELECT_I, 2520 DL, VTList, Cond, ShiftRightHi, 2521 IsSRA ? Ext : DAG.getConstant(0, DL, VT), Or, 2522 ShiftRightHi); 2523 } 2524 2525 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or); 2526 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, 2527 IsSRA ? Ext : DAG.getConstant(0, DL, VT), ShiftRightHi); 2528 2529 SDValue Ops[2] = {Lo, Hi}; 2530 return DAG.getMergeValues(Ops, DL); 2531 } 2532 2533 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD, 2534 SDValue Chain, SDValue Src, unsigned Offset) { 2535 SDValue Ptr = LD->getBasePtr(); 2536 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT(); 2537 EVT BasePtrVT = Ptr.getValueType(); 2538 SDLoc DL(LD); 2539 SDVTList VTList = DAG.getVTList(VT, MVT::Other); 2540 2541 if (Offset) 2542 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr, 2543 DAG.getConstant(Offset, DL, BasePtrVT)); 2544 2545 SDValue Ops[] = { Chain, Ptr, Src }; 2546 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT, 2547 LD->getMemOperand()); 2548 } 2549 2550 // Expand an unaligned 32 or 64-bit integer load node. 2551 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const { 2552 LoadSDNode *LD = cast<LoadSDNode>(Op); 2553 EVT MemVT = LD->getMemoryVT(); 2554 2555 if (Subtarget.systemSupportsUnalignedAccess()) 2556 return Op; 2557 2558 // Return if load is aligned or if MemVT is neither i32 nor i64. 2559 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) || 2560 ((MemVT != MVT::i32) && (MemVT != MVT::i64))) 2561 return SDValue(); 2562 2563 bool IsLittle = Subtarget.isLittle(); 2564 EVT VT = Op.getValueType(); 2565 ISD::LoadExtType ExtType = LD->getExtensionType(); 2566 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT); 2567 2568 assert((VT == MVT::i32) || (VT == MVT::i64)); 2569 2570 // Expand 2571 // (set dst, (i64 (load baseptr))) 2572 // to 2573 // (set tmp, (ldl (add baseptr, 7), undef)) 2574 // (set dst, (ldr baseptr, tmp)) 2575 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) { 2576 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef, 2577 IsLittle ? 7 : 0); 2578 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL, 2579 IsLittle ? 0 : 7); 2580 } 2581 2582 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef, 2583 IsLittle ? 3 : 0); 2584 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL, 2585 IsLittle ? 0 : 3); 2586 2587 // Expand 2588 // (set dst, (i32 (load baseptr))) or 2589 // (set dst, (i64 (sextload baseptr))) or 2590 // (set dst, (i64 (extload baseptr))) 2591 // to 2592 // (set tmp, (lwl (add baseptr, 3), undef)) 2593 // (set dst, (lwr baseptr, tmp)) 2594 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) || 2595 (ExtType == ISD::EXTLOAD)) 2596 return LWR; 2597 2598 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD)); 2599 2600 // Expand 2601 // (set dst, (i64 (zextload baseptr))) 2602 // to 2603 // (set tmp0, (lwl (add baseptr, 3), undef)) 2604 // (set tmp1, (lwr baseptr, tmp0)) 2605 // (set tmp2, (shl tmp1, 32)) 2606 // (set dst, (srl tmp2, 32)) 2607 SDLoc DL(LD); 2608 SDValue Const32 = DAG.getConstant(32, DL, MVT::i32); 2609 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32); 2610 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32); 2611 SDValue Ops[] = { SRL, LWR.getValue(1) }; 2612 return DAG.getMergeValues(Ops, DL); 2613 } 2614 2615 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD, 2616 SDValue Chain, unsigned Offset) { 2617 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue(); 2618 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType(); 2619 SDLoc DL(SD); 2620 SDVTList VTList = DAG.getVTList(MVT::Other); 2621 2622 if (Offset) 2623 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr, 2624 DAG.getConstant(Offset, DL, BasePtrVT)); 2625 2626 SDValue Ops[] = { Chain, Value, Ptr }; 2627 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT, 2628 SD->getMemOperand()); 2629 } 2630 2631 // Expand an unaligned 32 or 64-bit integer store node. 2632 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG, 2633 bool IsLittle) { 2634 SDValue Value = SD->getValue(), Chain = SD->getChain(); 2635 EVT VT = Value.getValueType(); 2636 2637 // Expand 2638 // (store val, baseptr) or 2639 // (truncstore val, baseptr) 2640 // to 2641 // (swl val, (add baseptr, 3)) 2642 // (swr val, baseptr) 2643 if ((VT == MVT::i32) || SD->isTruncatingStore()) { 2644 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain, 2645 IsLittle ? 3 : 0); 2646 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3); 2647 } 2648 2649 assert(VT == MVT::i64); 2650 2651 // Expand 2652 // (store val, baseptr) 2653 // to 2654 // (sdl val, (add baseptr, 7)) 2655 // (sdr val, baseptr) 2656 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0); 2657 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7); 2658 } 2659 2660 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr). 2661 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG, 2662 bool SingleFloat) { 2663 SDValue Val = SD->getValue(); 2664 2665 if (Val.getOpcode() != ISD::FP_TO_SINT || 2666 (Val.getValueSizeInBits() > 32 && SingleFloat)) 2667 return SDValue(); 2668 2669 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits()); 2670 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy, 2671 Val.getOperand(0)); 2672 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(), 2673 SD->getPointerInfo(), SD->getAlignment(), 2674 SD->getMemOperand()->getFlags()); 2675 } 2676 2677 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const { 2678 StoreSDNode *SD = cast<StoreSDNode>(Op); 2679 EVT MemVT = SD->getMemoryVT(); 2680 2681 // Lower unaligned integer stores. 2682 if (!Subtarget.systemSupportsUnalignedAccess() && 2683 (SD->getAlignment() < MemVT.getSizeInBits() / 8) && 2684 ((MemVT == MVT::i32) || (MemVT == MVT::i64))) 2685 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle()); 2686 2687 return lowerFP_TO_SINT_STORE(SD, DAG, Subtarget.isSingleFloat()); 2688 } 2689 2690 SDValue MipsTargetLowering::lowerEH_DWARF_CFA(SDValue Op, 2691 SelectionDAG &DAG) const { 2692 2693 // Return a fixed StackObject with offset 0 which points to the old stack 2694 // pointer. 2695 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 2696 EVT ValTy = Op->getValueType(0); 2697 int FI = MFI.CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false); 2698 return DAG.getFrameIndex(FI, ValTy); 2699 } 2700 2701 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op, 2702 SelectionDAG &DAG) const { 2703 if (Op.getValueSizeInBits() > 32 && Subtarget.isSingleFloat()) 2704 return SDValue(); 2705 2706 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits()); 2707 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy, 2708 Op.getOperand(0)); 2709 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc); 2710 } 2711 2712 //===----------------------------------------------------------------------===// 2713 // Calling Convention Implementation 2714 //===----------------------------------------------------------------------===// 2715 2716 //===----------------------------------------------------------------------===// 2717 // TODO: Implement a generic logic using tblgen that can support this. 2718 // Mips O32 ABI rules: 2719 // --- 2720 // i32 - Passed in A0, A1, A2, A3 and stack 2721 // f32 - Only passed in f32 registers if no int reg has been used yet to hold 2722 // an argument. Otherwise, passed in A1, A2, A3 and stack. 2723 // f64 - Only passed in two aliased f32 registers if no int reg has been used 2724 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is 2725 // not used, it must be shadowed. If only A3 is available, shadow it and 2726 // go to stack. 2727 // vXiX - Received as scalarized i32s, passed in A0 - A3 and the stack. 2728 // vXf32 - Passed in either a pair of registers {A0, A1}, {A2, A3} or {A0 - A3} 2729 // with the remainder spilled to the stack. 2730 // vXf64 - Passed in either {A0, A1, A2, A3} or {A2, A3} and in both cases 2731 // spilling the remainder to the stack. 2732 // 2733 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack. 2734 //===----------------------------------------------------------------------===// 2735 2736 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT, 2737 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 2738 CCState &State, ArrayRef<MCPhysReg> F64Regs) { 2739 const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>( 2740 State.getMachineFunction().getSubtarget()); 2741 2742 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 }; 2743 2744 const MipsCCState * MipsState = static_cast<MipsCCState *>(&State); 2745 2746 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 }; 2747 2748 static const MCPhysReg FloatVectorIntRegs[] = { Mips::A0, Mips::A2 }; 2749 2750 // Do not process byval args here. 2751 if (ArgFlags.isByVal()) 2752 return true; 2753 2754 // Promote i8 and i16 2755 if (ArgFlags.isInReg() && !Subtarget.isLittle()) { 2756 if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) { 2757 LocVT = MVT::i32; 2758 if (ArgFlags.isSExt()) 2759 LocInfo = CCValAssign::SExtUpper; 2760 else if (ArgFlags.isZExt()) 2761 LocInfo = CCValAssign::ZExtUpper; 2762 else 2763 LocInfo = CCValAssign::AExtUpper; 2764 } 2765 } 2766 2767 // Promote i8 and i16 2768 if (LocVT == MVT::i8 || LocVT == MVT::i16) { 2769 LocVT = MVT::i32; 2770 if (ArgFlags.isSExt()) 2771 LocInfo = CCValAssign::SExt; 2772 else if (ArgFlags.isZExt()) 2773 LocInfo = CCValAssign::ZExt; 2774 else 2775 LocInfo = CCValAssign::AExt; 2776 } 2777 2778 unsigned Reg; 2779 2780 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following 2781 // is true: function is vararg, argument is 3rd or higher, there is previous 2782 // argument which is not f32 or f64. 2783 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 || 2784 State.getFirstUnallocated(F32Regs) != ValNo; 2785 unsigned OrigAlign = ArgFlags.getOrigAlign(); 2786 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8); 2787 bool isVectorFloat = MipsState->WasOriginalArgVectorFloat(ValNo); 2788 2789 // The MIPS vector ABI for floats passes them in a pair of registers 2790 if (ValVT == MVT::i32 && isVectorFloat) { 2791 // This is the start of an vector that was scalarized into an unknown number 2792 // of components. It doesn't matter how many there are. Allocate one of the 2793 // notional 8 byte aligned registers which map onto the argument stack, and 2794 // shadow the register lost to alignment requirements. 2795 if (ArgFlags.isSplit()) { 2796 Reg = State.AllocateReg(FloatVectorIntRegs); 2797 if (Reg == Mips::A2) 2798 State.AllocateReg(Mips::A1); 2799 else if (Reg == 0) 2800 State.AllocateReg(Mips::A3); 2801 } else { 2802 // If we're an intermediate component of the split, we can just attempt to 2803 // allocate a register directly. 2804 Reg = State.AllocateReg(IntRegs); 2805 } 2806 } else if (ValVT == MVT::i32 || 2807 (ValVT == MVT::f32 && AllocateFloatsInIntReg)) { 2808 Reg = State.AllocateReg(IntRegs); 2809 // If this is the first part of an i64 arg, 2810 // the allocated register must be either A0 or A2. 2811 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3)) 2812 Reg = State.AllocateReg(IntRegs); 2813 LocVT = MVT::i32; 2814 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) { 2815 // Allocate int register and shadow next int register. If first 2816 // available register is Mips::A1 or Mips::A3, shadow it too. 2817 Reg = State.AllocateReg(IntRegs); 2818 if (Reg == Mips::A1 || Reg == Mips::A3) 2819 Reg = State.AllocateReg(IntRegs); 2820 State.AllocateReg(IntRegs); 2821 LocVT = MVT::i32; 2822 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) { 2823 // we are guaranteed to find an available float register 2824 if (ValVT == MVT::f32) { 2825 Reg = State.AllocateReg(F32Regs); 2826 // Shadow int register 2827 State.AllocateReg(IntRegs); 2828 } else { 2829 Reg = State.AllocateReg(F64Regs); 2830 // Shadow int registers 2831 unsigned Reg2 = State.AllocateReg(IntRegs); 2832 if (Reg2 == Mips::A1 || Reg2 == Mips::A3) 2833 State.AllocateReg(IntRegs); 2834 State.AllocateReg(IntRegs); 2835 } 2836 } else 2837 llvm_unreachable("Cannot handle this ValVT."); 2838 2839 if (!Reg) { 2840 unsigned Offset = State.AllocateStack(ValVT.getStoreSize(), OrigAlign); 2841 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 2842 } else 2843 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 2844 2845 return false; 2846 } 2847 2848 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT, 2849 MVT LocVT, CCValAssign::LocInfo LocInfo, 2850 ISD::ArgFlagsTy ArgFlags, CCState &State) { 2851 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 }; 2852 2853 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs); 2854 } 2855 2856 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT, 2857 MVT LocVT, CCValAssign::LocInfo LocInfo, 2858 ISD::ArgFlagsTy ArgFlags, CCState &State) { 2859 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 }; 2860 2861 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs); 2862 } 2863 2864 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT, 2865 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 2866 CCState &State) LLVM_ATTRIBUTE_UNUSED; 2867 2868 #include "MipsGenCallingConv.inc" 2869 2870 CCAssignFn *MipsTargetLowering::CCAssignFnForCall() const{ 2871 return CC_Mips_FixedArg; 2872 } 2873 2874 CCAssignFn *MipsTargetLowering::CCAssignFnForReturn() const{ 2875 return RetCC_Mips; 2876 } 2877 //===----------------------------------------------------------------------===// 2878 // Call Calling Convention Implementation 2879 //===----------------------------------------------------------------------===// 2880 2881 // Return next O32 integer argument register. 2882 static unsigned getNextIntArgReg(unsigned Reg) { 2883 assert((Reg == Mips::A0) || (Reg == Mips::A2)); 2884 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3; 2885 } 2886 2887 SDValue MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset, 2888 SDValue Chain, SDValue Arg, 2889 const SDLoc &DL, bool IsTailCall, 2890 SelectionDAG &DAG) const { 2891 if (!IsTailCall) { 2892 SDValue PtrOff = 2893 DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr, 2894 DAG.getIntPtrConstant(Offset, DL)); 2895 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo()); 2896 } 2897 2898 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 2899 int FI = MFI.CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false); 2900 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 2901 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(), 2902 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 2903 } 2904 2905 void MipsTargetLowering:: 2906 getOpndList(SmallVectorImpl<SDValue> &Ops, 2907 std::deque<std::pair<unsigned, SDValue>> &RegsToPass, 2908 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage, 2909 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee, 2910 SDValue Chain) const { 2911 // Insert node "GP copy globalreg" before call to function. 2912 // 2913 // R_MIPS_CALL* operators (emitted when non-internal functions are called 2914 // in PIC mode) allow symbols to be resolved via lazy binding. 2915 // The lazy binding stub requires GP to point to the GOT. 2916 // Note that we don't need GP to point to the GOT for indirect calls 2917 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates 2918 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs 2919 // used for the function (that is, Mips linker doesn't generate lazy binding 2920 // stub for a function whose address is taken in the program). 2921 if (IsPICCall && !InternalLinkage && IsCallReloc) { 2922 unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP; 2923 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32; 2924 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty))); 2925 } 2926 2927 // Build a sequence of copy-to-reg nodes chained together with token 2928 // chain and flag operands which copy the outgoing args into registers. 2929 // The InFlag in necessary since all emitted instructions must be 2930 // stuck together. 2931 SDValue InFlag; 2932 2933 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2934 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first, 2935 RegsToPass[i].second, InFlag); 2936 InFlag = Chain.getValue(1); 2937 } 2938 2939 // Add argument registers to the end of the list so that they are 2940 // known live into the call. 2941 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2942 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first, 2943 RegsToPass[i].second.getValueType())); 2944 2945 // Add a register mask operand representing the call-preserved registers. 2946 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 2947 const uint32_t *Mask = 2948 TRI->getCallPreservedMask(CLI.DAG.getMachineFunction(), CLI.CallConv); 2949 assert(Mask && "Missing call preserved mask for calling convention"); 2950 if (Subtarget.inMips16HardFloat()) { 2951 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) { 2952 StringRef Sym = G->getGlobal()->getName(); 2953 Function *F = G->getGlobal()->getParent()->getFunction(Sym); 2954 if (F && F->hasFnAttribute("__Mips16RetHelper")) { 2955 Mask = MipsRegisterInfo::getMips16RetHelperMask(); 2956 } 2957 } 2958 } 2959 Ops.push_back(CLI.DAG.getRegisterMask(Mask)); 2960 2961 if (InFlag.getNode()) 2962 Ops.push_back(InFlag); 2963 } 2964 2965 void MipsTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 2966 SDNode *Node) const { 2967 switch (MI.getOpcode()) { 2968 default: 2969 return; 2970 case Mips::JALR: 2971 case Mips::JALRPseudo: 2972 case Mips::JALR64: 2973 case Mips::JALR64Pseudo: 2974 case Mips::JALR16_MM: 2975 case Mips::JALRC16_MMR6: 2976 case Mips::TAILCALLREG: 2977 case Mips::TAILCALLREG64: 2978 case Mips::TAILCALLR6REG: 2979 case Mips::TAILCALL64R6REG: 2980 case Mips::TAILCALLREG_MM: 2981 case Mips::TAILCALLREG_MMR6: { 2982 if (!EmitJalrReloc || 2983 Subtarget.inMips16Mode() || 2984 !isPositionIndependent() || 2985 Node->getNumOperands() < 1 || 2986 Node->getOperand(0).getNumOperands() < 2) { 2987 return; 2988 } 2989 // We are after the callee address, set by LowerCall(). 2990 // If added to MI, asm printer will emit .reloc R_MIPS_JALR for the 2991 // symbol. 2992 const SDValue TargetAddr = Node->getOperand(0).getOperand(1); 2993 StringRef Sym; 2994 if (const GlobalAddressSDNode *G = 2995 dyn_cast_or_null<const GlobalAddressSDNode>(TargetAddr)) { 2996 Sym = G->getGlobal()->getName(); 2997 } 2998 else if (const ExternalSymbolSDNode *ES = 2999 dyn_cast_or_null<const ExternalSymbolSDNode>(TargetAddr)) { 3000 Sym = ES->getSymbol(); 3001 } 3002 3003 if (Sym.empty()) 3004 return; 3005 3006 MachineFunction *MF = MI.getParent()->getParent(); 3007 MCSymbol *S = MF->getContext().getOrCreateSymbol(Sym); 3008 MI.addOperand(MachineOperand::CreateMCSymbol(S, MipsII::MO_JALR)); 3009 } 3010 } 3011 } 3012 3013 /// LowerCall - functions arguments are copied from virtual regs to 3014 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted. 3015 SDValue 3016 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 3017 SmallVectorImpl<SDValue> &InVals) const { 3018 SelectionDAG &DAG = CLI.DAG; 3019 SDLoc DL = CLI.DL; 3020 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 3021 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 3022 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 3023 SDValue Chain = CLI.Chain; 3024 SDValue Callee = CLI.Callee; 3025 bool &IsTailCall = CLI.IsTailCall; 3026 CallingConv::ID CallConv = CLI.CallConv; 3027 bool IsVarArg = CLI.IsVarArg; 3028 3029 MachineFunction &MF = DAG.getMachineFunction(); 3030 MachineFrameInfo &MFI = MF.getFrameInfo(); 3031 const TargetFrameLowering *TFL = Subtarget.getFrameLowering(); 3032 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>(); 3033 bool IsPIC = isPositionIndependent(); 3034 3035 // Analyze operands of the call, assigning locations to each operand. 3036 SmallVector<CCValAssign, 16> ArgLocs; 3037 MipsCCState CCInfo( 3038 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(), 3039 MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget)); 3040 3041 const ExternalSymbolSDNode *ES = 3042 dyn_cast_or_null<const ExternalSymbolSDNode>(Callee.getNode()); 3043 3044 // There is one case where CALLSEQ_START..CALLSEQ_END can be nested, which 3045 // is during the lowering of a call with a byval argument which produces 3046 // a call to memcpy. For the O32 case, this causes the caller to allocate 3047 // stack space for the reserved argument area for the callee, then recursively 3048 // again for the memcpy call. In the NEWABI case, this doesn't occur as those 3049 // ABIs mandate that the callee allocates the reserved argument area. We do 3050 // still produce nested CALLSEQ_START..CALLSEQ_END with zero space though. 3051 // 3052 // If the callee has a byval argument and memcpy is used, we are mandated 3053 // to already have produced a reserved argument area for the callee for O32. 3054 // Therefore, the reserved argument area can be reused for both calls. 3055 // 3056 // Other cases of calling memcpy cannot have a chain with a CALLSEQ_START 3057 // present, as we have yet to hook that node onto the chain. 3058 // 3059 // Hence, the CALLSEQ_START and CALLSEQ_END nodes can be eliminated in this 3060 // case. GCC does a similar trick, in that wherever possible, it calculates 3061 // the maximum out going argument area (including the reserved area), and 3062 // preallocates the stack space on entrance to the caller. 3063 // 3064 // FIXME: We should do the same for efficiency and space. 3065 3066 // Note: The check on the calling convention below must match 3067 // MipsABIInfo::GetCalleeAllocdArgSizeInBytes(). 3068 bool MemcpyInByVal = ES && 3069 StringRef(ES->getSymbol()) == StringRef("memcpy") && 3070 CallConv != CallingConv::Fast && 3071 Chain.getOpcode() == ISD::CALLSEQ_START; 3072 3073 // Allocate the reserved argument area. It seems strange to do this from the 3074 // caller side but removing it breaks the frame size calculation. 3075 unsigned ReservedArgArea = 3076 MemcpyInByVal ? 0 : ABI.GetCalleeAllocdArgSizeInBytes(CallConv); 3077 CCInfo.AllocateStack(ReservedArgArea, 1); 3078 3079 CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(), 3080 ES ? ES->getSymbol() : nullptr); 3081 3082 // Get a count of how many bytes are to be pushed on the stack. 3083 unsigned NextStackOffset = CCInfo.getNextStackOffset(); 3084 3085 // Check if it's really possible to do a tail call. Restrict it to functions 3086 // that are part of this compilation unit. 3087 bool InternalLinkage = false; 3088 if (IsTailCall) { 3089 IsTailCall = isEligibleForTailCallOptimization( 3090 CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>()); 3091 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3092 InternalLinkage = G->getGlobal()->hasInternalLinkage(); 3093 IsTailCall &= (InternalLinkage || G->getGlobal()->hasLocalLinkage() || 3094 G->getGlobal()->hasPrivateLinkage() || 3095 G->getGlobal()->hasHiddenVisibility() || 3096 G->getGlobal()->hasProtectedVisibility()); 3097 } 3098 } 3099 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) 3100 report_fatal_error("failed to perform tail call elimination on a call " 3101 "site marked musttail"); 3102 3103 if (IsTailCall) 3104 ++NumTailCalls; 3105 3106 // Chain is the output chain of the last Load/Store or CopyToReg node. 3107 // ByValChain is the output chain of the last Memcpy node created for copying 3108 // byval arguments to the stack. 3109 unsigned StackAlignment = TFL->getStackAlignment(); 3110 NextStackOffset = alignTo(NextStackOffset, StackAlignment); 3111 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, DL, true); 3112 3113 if (!(IsTailCall || MemcpyInByVal)) 3114 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffset, 0, DL); 3115 3116 SDValue StackPtr = 3117 DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP, 3118 getPointerTy(DAG.getDataLayout())); 3119 3120 std::deque<std::pair<unsigned, SDValue>> RegsToPass; 3121 SmallVector<SDValue, 8> MemOpChains; 3122 3123 CCInfo.rewindByValRegsInfo(); 3124 3125 // Walk the register/memloc assignments, inserting copies/loads. 3126 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3127 SDValue Arg = OutVals[i]; 3128 CCValAssign &VA = ArgLocs[i]; 3129 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT(); 3130 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3131 bool UseUpperBits = false; 3132 3133 // ByVal Arg. 3134 if (Flags.isByVal()) { 3135 unsigned FirstByValReg, LastByValReg; 3136 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed(); 3137 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg); 3138 3139 assert(Flags.getByValSize() && 3140 "ByVal args of size 0 should have been ignored by front-end."); 3141 assert(ByValIdx < CCInfo.getInRegsParamsCount()); 3142 assert(!IsTailCall && 3143 "Do not tail-call optimize if there is a byval argument."); 3144 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg, 3145 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(), 3146 VA); 3147 CCInfo.nextInRegsParam(); 3148 continue; 3149 } 3150 3151 // Promote the value if needed. 3152 switch (VA.getLocInfo()) { 3153 default: 3154 llvm_unreachable("Unknown loc info!"); 3155 case CCValAssign::Full: 3156 if (VA.isRegLoc()) { 3157 if ((ValVT == MVT::f32 && LocVT == MVT::i32) || 3158 (ValVT == MVT::f64 && LocVT == MVT::i64) || 3159 (ValVT == MVT::i64 && LocVT == MVT::f64)) 3160 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg); 3161 else if (ValVT == MVT::f64 && LocVT == MVT::i32) { 3162 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, 3163 Arg, DAG.getConstant(0, DL, MVT::i32)); 3164 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, 3165 Arg, DAG.getConstant(1, DL, MVT::i32)); 3166 if (!Subtarget.isLittle()) 3167 std::swap(Lo, Hi); 3168 Register LocRegLo = VA.getLocReg(); 3169 unsigned LocRegHigh = getNextIntArgReg(LocRegLo); 3170 RegsToPass.push_back(std::make_pair(LocRegLo, Lo)); 3171 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi)); 3172 continue; 3173 } 3174 } 3175 break; 3176 case CCValAssign::BCvt: 3177 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg); 3178 break; 3179 case CCValAssign::SExtUpper: 3180 UseUpperBits = true; 3181 LLVM_FALLTHROUGH; 3182 case CCValAssign::SExt: 3183 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg); 3184 break; 3185 case CCValAssign::ZExtUpper: 3186 UseUpperBits = true; 3187 LLVM_FALLTHROUGH; 3188 case CCValAssign::ZExt: 3189 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg); 3190 break; 3191 case CCValAssign::AExtUpper: 3192 UseUpperBits = true; 3193 LLVM_FALLTHROUGH; 3194 case CCValAssign::AExt: 3195 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg); 3196 break; 3197 } 3198 3199 if (UseUpperBits) { 3200 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits(); 3201 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits(); 3202 Arg = DAG.getNode( 3203 ISD::SHL, DL, VA.getLocVT(), Arg, 3204 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT())); 3205 } 3206 3207 // Arguments that can be passed on register must be kept at 3208 // RegsToPass vector 3209 if (VA.isRegLoc()) { 3210 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3211 continue; 3212 } 3213 3214 // Register can't get to this point... 3215 assert(VA.isMemLoc()); 3216 3217 // emit ISD::STORE whichs stores the 3218 // parameter value to a stack Location 3219 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(), 3220 Chain, Arg, DL, IsTailCall, DAG)); 3221 } 3222 3223 // Transform all store nodes into one single node because all store 3224 // nodes are independent of each other. 3225 if (!MemOpChains.empty()) 3226 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3227 3228 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 3229 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 3230 // node so that legalize doesn't hack it. 3231 3232 EVT Ty = Callee.getValueType(); 3233 bool GlobalOrExternal = false, IsCallReloc = false; 3234 3235 // The long-calls feature is ignored in case of PIC. 3236 // While we do not support -mshared / -mno-shared properly, 3237 // ignore long-calls in case of -mabicalls too. 3238 if (!Subtarget.isABICalls() && !IsPIC) { 3239 // If the function should be called using "long call", 3240 // get its address into a register to prevent using 3241 // of the `jal` instruction for the direct call. 3242 if (auto *N = dyn_cast<ExternalSymbolSDNode>(Callee)) { 3243 if (Subtarget.useLongCalls()) 3244 Callee = Subtarget.hasSym32() 3245 ? getAddrNonPIC(N, SDLoc(N), Ty, DAG) 3246 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG); 3247 } else if (auto *N = dyn_cast<GlobalAddressSDNode>(Callee)) { 3248 bool UseLongCalls = Subtarget.useLongCalls(); 3249 // If the function has long-call/far/near attribute 3250 // it overrides command line switch pased to the backend. 3251 if (auto *F = dyn_cast<Function>(N->getGlobal())) { 3252 if (F->hasFnAttribute("long-call")) 3253 UseLongCalls = true; 3254 else if (F->hasFnAttribute("short-call")) 3255 UseLongCalls = false; 3256 } 3257 if (UseLongCalls) 3258 Callee = Subtarget.hasSym32() 3259 ? getAddrNonPIC(N, SDLoc(N), Ty, DAG) 3260 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG); 3261 } 3262 } 3263 3264 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3265 if (IsPIC) { 3266 const GlobalValue *Val = G->getGlobal(); 3267 InternalLinkage = Val->hasInternalLinkage(); 3268 3269 if (InternalLinkage) 3270 Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64()); 3271 else if (Subtarget.useXGOT()) { 3272 Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16, 3273 MipsII::MO_CALL_LO16, Chain, 3274 FuncInfo->callPtrInfo(Val)); 3275 IsCallReloc = true; 3276 } else { 3277 Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain, 3278 FuncInfo->callPtrInfo(Val)); 3279 IsCallReloc = true; 3280 } 3281 } else 3282 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, 3283 getPointerTy(DAG.getDataLayout()), 0, 3284 MipsII::MO_NO_FLAG); 3285 GlobalOrExternal = true; 3286 } 3287 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 3288 const char *Sym = S->getSymbol(); 3289 3290 if (!IsPIC) // static 3291 Callee = DAG.getTargetExternalSymbol( 3292 Sym, getPointerTy(DAG.getDataLayout()), MipsII::MO_NO_FLAG); 3293 else if (Subtarget.useXGOT()) { 3294 Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16, 3295 MipsII::MO_CALL_LO16, Chain, 3296 FuncInfo->callPtrInfo(Sym)); 3297 IsCallReloc = true; 3298 } else { // PIC 3299 Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain, 3300 FuncInfo->callPtrInfo(Sym)); 3301 IsCallReloc = true; 3302 } 3303 3304 GlobalOrExternal = true; 3305 } 3306 3307 SmallVector<SDValue, 8> Ops(1, Chain); 3308 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3309 3310 getOpndList(Ops, RegsToPass, IsPIC, GlobalOrExternal, InternalLinkage, 3311 IsCallReloc, CLI, Callee, Chain); 3312 3313 if (IsTailCall) { 3314 MF.getFrameInfo().setHasTailCall(); 3315 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops); 3316 } 3317 3318 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops); 3319 SDValue InFlag = Chain.getValue(1); 3320 3321 // Create the CALLSEQ_END node in the case of where it is not a call to 3322 // memcpy. 3323 if (!(MemcpyInByVal)) { 3324 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal, 3325 DAG.getIntPtrConstant(0, DL, true), InFlag, DL); 3326 InFlag = Chain.getValue(1); 3327 } 3328 3329 // Handle result values, copying them out of physregs into vregs that we 3330 // return. 3331 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3332 InVals, CLI); 3333 } 3334 3335 /// LowerCallResult - Lower the result values of a call into the 3336 /// appropriate copies out of appropriate physical registers. 3337 SDValue MipsTargetLowering::LowerCallResult( 3338 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 3339 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 3340 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 3341 TargetLowering::CallLoweringInfo &CLI) const { 3342 // Assign locations to each value returned by this call. 3343 SmallVector<CCValAssign, 16> RVLocs; 3344 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 3345 *DAG.getContext()); 3346 3347 const ExternalSymbolSDNode *ES = 3348 dyn_cast_or_null<const ExternalSymbolSDNode>(CLI.Callee.getNode()); 3349 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI.RetTy, 3350 ES ? ES->getSymbol() : nullptr); 3351 3352 // Copy all of the result registers out of their specified physreg. 3353 for (unsigned i = 0; i != RVLocs.size(); ++i) { 3354 CCValAssign &VA = RVLocs[i]; 3355 assert(VA.isRegLoc() && "Can only return in registers!"); 3356 3357 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(), 3358 RVLocs[i].getLocVT(), InFlag); 3359 Chain = Val.getValue(1); 3360 InFlag = Val.getValue(2); 3361 3362 if (VA.isUpperBitsInLoc()) { 3363 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits(); 3364 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits(); 3365 unsigned Shift = 3366 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA; 3367 Val = DAG.getNode( 3368 Shift, DL, VA.getLocVT(), Val, 3369 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT())); 3370 } 3371 3372 switch (VA.getLocInfo()) { 3373 default: 3374 llvm_unreachable("Unknown loc info!"); 3375 case CCValAssign::Full: 3376 break; 3377 case CCValAssign::BCvt: 3378 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 3379 break; 3380 case CCValAssign::AExt: 3381 case CCValAssign::AExtUpper: 3382 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 3383 break; 3384 case CCValAssign::ZExt: 3385 case CCValAssign::ZExtUpper: 3386 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 3387 DAG.getValueType(VA.getValVT())); 3388 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 3389 break; 3390 case CCValAssign::SExt: 3391 case CCValAssign::SExtUpper: 3392 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 3393 DAG.getValueType(VA.getValVT())); 3394 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 3395 break; 3396 } 3397 3398 InVals.push_back(Val); 3399 } 3400 3401 return Chain; 3402 } 3403 3404 static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA, 3405 EVT ArgVT, const SDLoc &DL, 3406 SelectionDAG &DAG) { 3407 MVT LocVT = VA.getLocVT(); 3408 EVT ValVT = VA.getValVT(); 3409 3410 // Shift into the upper bits if necessary. 3411 switch (VA.getLocInfo()) { 3412 default: 3413 break; 3414 case CCValAssign::AExtUpper: 3415 case CCValAssign::SExtUpper: 3416 case CCValAssign::ZExtUpper: { 3417 unsigned ValSizeInBits = ArgVT.getSizeInBits(); 3418 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits(); 3419 unsigned Opcode = 3420 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA; 3421 Val = DAG.getNode( 3422 Opcode, DL, VA.getLocVT(), Val, 3423 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT())); 3424 break; 3425 } 3426 } 3427 3428 // If this is an value smaller than the argument slot size (32-bit for O32, 3429 // 64-bit for N32/N64), it has been promoted in some way to the argument slot 3430 // size. Extract the value and insert any appropriate assertions regarding 3431 // sign/zero extension. 3432 switch (VA.getLocInfo()) { 3433 default: 3434 llvm_unreachable("Unknown loc info!"); 3435 case CCValAssign::Full: 3436 break; 3437 case CCValAssign::AExtUpper: 3438 case CCValAssign::AExt: 3439 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 3440 break; 3441 case CCValAssign::SExtUpper: 3442 case CCValAssign::SExt: 3443 Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT)); 3444 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 3445 break; 3446 case CCValAssign::ZExtUpper: 3447 case CCValAssign::ZExt: 3448 Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT)); 3449 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 3450 break; 3451 case CCValAssign::BCvt: 3452 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 3453 break; 3454 } 3455 3456 return Val; 3457 } 3458 3459 //===----------------------------------------------------------------------===// 3460 // Formal Arguments Calling Convention Implementation 3461 //===----------------------------------------------------------------------===// 3462 /// LowerFormalArguments - transform physical registers into virtual registers 3463 /// and generate load operations for arguments places on the stack. 3464 SDValue MipsTargetLowering::LowerFormalArguments( 3465 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 3466 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 3467 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3468 MachineFunction &MF = DAG.getMachineFunction(); 3469 MachineFrameInfo &MFI = MF.getFrameInfo(); 3470 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>(); 3471 3472 MipsFI->setVarArgsFrameIndex(0); 3473 3474 // Used with vargs to acumulate store chains. 3475 std::vector<SDValue> OutChains; 3476 3477 // Assign locations to all of the incoming arguments. 3478 SmallVector<CCValAssign, 16> ArgLocs; 3479 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, 3480 *DAG.getContext()); 3481 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1); 3482 const Function &Func = DAG.getMachineFunction().getFunction(); 3483 Function::const_arg_iterator FuncArg = Func.arg_begin(); 3484 3485 if (Func.hasFnAttribute("interrupt") && !Func.arg_empty()) 3486 report_fatal_error( 3487 "Functions with the interrupt attribute cannot have arguments!"); 3488 3489 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg); 3490 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(), 3491 CCInfo.getInRegsParamsCount() > 0); 3492 3493 unsigned CurArgIdx = 0; 3494 CCInfo.rewindByValRegsInfo(); 3495 3496 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3497 CCValAssign &VA = ArgLocs[i]; 3498 if (Ins[i].isOrigArg()) { 3499 std::advance(FuncArg, Ins[i].getOrigArgIndex() - CurArgIdx); 3500 CurArgIdx = Ins[i].getOrigArgIndex(); 3501 } 3502 EVT ValVT = VA.getValVT(); 3503 ISD::ArgFlagsTy Flags = Ins[i].Flags; 3504 bool IsRegLoc = VA.isRegLoc(); 3505 3506 if (Flags.isByVal()) { 3507 assert(Ins[i].isOrigArg() && "Byval arguments cannot be implicit"); 3508 unsigned FirstByValReg, LastByValReg; 3509 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed(); 3510 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg); 3511 3512 assert(Flags.getByValSize() && 3513 "ByVal args of size 0 should have been ignored by front-end."); 3514 assert(ByValIdx < CCInfo.getInRegsParamsCount()); 3515 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg, 3516 FirstByValReg, LastByValReg, VA, CCInfo); 3517 CCInfo.nextInRegsParam(); 3518 continue; 3519 } 3520 3521 // Arguments stored on registers 3522 if (IsRegLoc) { 3523 MVT RegVT = VA.getLocVT(); 3524 Register ArgReg = VA.getLocReg(); 3525 const TargetRegisterClass *RC = getRegClassFor(RegVT); 3526 3527 // Transform the arguments stored on 3528 // physical registers into virtual ones 3529 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC); 3530 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT); 3531 3532 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG); 3533 3534 // Handle floating point arguments passed in integer registers and 3535 // long double arguments passed in floating point registers. 3536 if ((RegVT == MVT::i32 && ValVT == MVT::f32) || 3537 (RegVT == MVT::i64 && ValVT == MVT::f64) || 3538 (RegVT == MVT::f64 && ValVT == MVT::i64)) 3539 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue); 3540 else if (ABI.IsO32() && RegVT == MVT::i32 && 3541 ValVT == MVT::f64) { 3542 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(), 3543 getNextIntArgReg(ArgReg), RC); 3544 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT); 3545 if (!Subtarget.isLittle()) 3546 std::swap(ArgValue, ArgValue2); 3547 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, 3548 ArgValue, ArgValue2); 3549 } 3550 3551 InVals.push_back(ArgValue); 3552 } else { // VA.isRegLoc() 3553 MVT LocVT = VA.getLocVT(); 3554 3555 if (ABI.IsO32()) { 3556 // We ought to be able to use LocVT directly but O32 sets it to i32 3557 // when allocating floating point values to integer registers. 3558 // This shouldn't influence how we load the value into registers unless 3559 // we are targeting softfloat. 3560 if (VA.getValVT().isFloatingPoint() && !Subtarget.useSoftFloat()) 3561 LocVT = VA.getValVT(); 3562 } 3563 3564 // sanity check 3565 assert(VA.isMemLoc()); 3566 3567 // The stack pointer offset is relative to the caller stack frame. 3568 int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8, 3569 VA.getLocMemOffset(), true); 3570 3571 // Create load nodes to retrieve arguments from the stack 3572 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3573 SDValue ArgValue = DAG.getLoad( 3574 LocVT, DL, Chain, FIN, 3575 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3576 OutChains.push_back(ArgValue.getValue(1)); 3577 3578 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG); 3579 3580 InVals.push_back(ArgValue); 3581 } 3582 } 3583 3584 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3585 // The mips ABIs for returning structs by value requires that we copy 3586 // the sret argument into $v0 for the return. Save the argument into 3587 // a virtual register so that we can access it from the return points. 3588 if (Ins[i].Flags.isSRet()) { 3589 unsigned Reg = MipsFI->getSRetReturnReg(); 3590 if (!Reg) { 3591 Reg = MF.getRegInfo().createVirtualRegister( 3592 getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32)); 3593 MipsFI->setSRetReturnReg(Reg); 3594 } 3595 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]); 3596 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain); 3597 break; 3598 } 3599 } 3600 3601 if (IsVarArg) 3602 writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo); 3603 3604 // All stores are grouped in one node to allow the matching between 3605 // the size of Ins and InVals. This only happens when on varg functions 3606 if (!OutChains.empty()) { 3607 OutChains.push_back(Chain); 3608 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 3609 } 3610 3611 return Chain; 3612 } 3613 3614 //===----------------------------------------------------------------------===// 3615 // Return Value Calling Convention Implementation 3616 //===----------------------------------------------------------------------===// 3617 3618 bool 3619 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 3620 MachineFunction &MF, bool IsVarArg, 3621 const SmallVectorImpl<ISD::OutputArg> &Outs, 3622 LLVMContext &Context) const { 3623 SmallVector<CCValAssign, 16> RVLocs; 3624 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 3625 return CCInfo.CheckReturn(Outs, RetCC_Mips); 3626 } 3627 3628 bool MipsTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, 3629 bool IsSigned) const { 3630 if ((ABI.IsN32() || ABI.IsN64()) && Type == MVT::i32) 3631 return true; 3632 3633 return IsSigned; 3634 } 3635 3636 SDValue 3637 MipsTargetLowering::LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 3638 const SDLoc &DL, 3639 SelectionDAG &DAG) const { 3640 MachineFunction &MF = DAG.getMachineFunction(); 3641 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>(); 3642 3643 MipsFI->setISR(); 3644 3645 return DAG.getNode(MipsISD::ERet, DL, MVT::Other, RetOps); 3646 } 3647 3648 SDValue 3649 MipsTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 3650 bool IsVarArg, 3651 const SmallVectorImpl<ISD::OutputArg> &Outs, 3652 const SmallVectorImpl<SDValue> &OutVals, 3653 const SDLoc &DL, SelectionDAG &DAG) const { 3654 // CCValAssign - represent the assignment of 3655 // the return value to a location 3656 SmallVector<CCValAssign, 16> RVLocs; 3657 MachineFunction &MF = DAG.getMachineFunction(); 3658 3659 // CCState - Info about the registers and stack slot. 3660 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 3661 3662 // Analyze return values. 3663 CCInfo.AnalyzeReturn(Outs, RetCC_Mips); 3664 3665 SDValue Flag; 3666 SmallVector<SDValue, 4> RetOps(1, Chain); 3667 3668 // Copy the result values into the output registers. 3669 for (unsigned i = 0; i != RVLocs.size(); ++i) { 3670 SDValue Val = OutVals[i]; 3671 CCValAssign &VA = RVLocs[i]; 3672 assert(VA.isRegLoc() && "Can only return in registers!"); 3673 bool UseUpperBits = false; 3674 3675 switch (VA.getLocInfo()) { 3676 default: 3677 llvm_unreachable("Unknown loc info!"); 3678 case CCValAssign::Full: 3679 break; 3680 case CCValAssign::BCvt: 3681 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val); 3682 break; 3683 case CCValAssign::AExtUpper: 3684 UseUpperBits = true; 3685 LLVM_FALLTHROUGH; 3686 case CCValAssign::AExt: 3687 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val); 3688 break; 3689 case CCValAssign::ZExtUpper: 3690 UseUpperBits = true; 3691 LLVM_FALLTHROUGH; 3692 case CCValAssign::ZExt: 3693 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val); 3694 break; 3695 case CCValAssign::SExtUpper: 3696 UseUpperBits = true; 3697 LLVM_FALLTHROUGH; 3698 case CCValAssign::SExt: 3699 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val); 3700 break; 3701 } 3702 3703 if (UseUpperBits) { 3704 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits(); 3705 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits(); 3706 Val = DAG.getNode( 3707 ISD::SHL, DL, VA.getLocVT(), Val, 3708 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT())); 3709 } 3710 3711 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag); 3712 3713 // Guarantee that all emitted copies are stuck together with flags. 3714 Flag = Chain.getValue(1); 3715 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3716 } 3717 3718 // The mips ABIs for returning structs by value requires that we copy 3719 // the sret argument into $v0 for the return. We saved the argument into 3720 // a virtual register in the entry block, so now we copy the value out 3721 // and into $v0. 3722 if (MF.getFunction().hasStructRetAttr()) { 3723 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>(); 3724 unsigned Reg = MipsFI->getSRetReturnReg(); 3725 3726 if (!Reg) 3727 llvm_unreachable("sret virtual register not created in the entry block"); 3728 SDValue Val = 3729 DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout())); 3730 unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0; 3731 3732 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag); 3733 Flag = Chain.getValue(1); 3734 RetOps.push_back(DAG.getRegister(V0, getPointerTy(DAG.getDataLayout()))); 3735 } 3736 3737 RetOps[0] = Chain; // Update chain. 3738 3739 // Add the flag if we have it. 3740 if (Flag.getNode()) 3741 RetOps.push_back(Flag); 3742 3743 // ISRs must use "eret". 3744 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt")) 3745 return LowerInterruptReturn(RetOps, DL, DAG); 3746 3747 // Standard return on Mips is a "jr $ra" 3748 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps); 3749 } 3750 3751 //===----------------------------------------------------------------------===// 3752 // Mips Inline Assembly Support 3753 //===----------------------------------------------------------------------===// 3754 3755 /// getConstraintType - Given a constraint letter, return the type of 3756 /// constraint it is for this target. 3757 MipsTargetLowering::ConstraintType 3758 MipsTargetLowering::getConstraintType(StringRef Constraint) const { 3759 // Mips specific constraints 3760 // GCC config/mips/constraints.md 3761 // 3762 // 'd' : An address register. Equivalent to r 3763 // unless generating MIPS16 code. 3764 // 'y' : Equivalent to r; retained for 3765 // backwards compatibility. 3766 // 'c' : A register suitable for use in an indirect 3767 // jump. This will always be $25 for -mabicalls. 3768 // 'l' : The lo register. 1 word storage. 3769 // 'x' : The hilo register pair. Double word storage. 3770 if (Constraint.size() == 1) { 3771 switch (Constraint[0]) { 3772 default : break; 3773 case 'd': 3774 case 'y': 3775 case 'f': 3776 case 'c': 3777 case 'l': 3778 case 'x': 3779 return C_RegisterClass; 3780 case 'R': 3781 return C_Memory; 3782 } 3783 } 3784 3785 if (Constraint == "ZC") 3786 return C_Memory; 3787 3788 return TargetLowering::getConstraintType(Constraint); 3789 } 3790 3791 /// Examine constraint type and operand type and determine a weight value. 3792 /// This object must already have been set up with the operand type 3793 /// and the current alternative constraint selected. 3794 TargetLowering::ConstraintWeight 3795 MipsTargetLowering::getSingleConstraintMatchWeight( 3796 AsmOperandInfo &info, const char *constraint) const { 3797 ConstraintWeight weight = CW_Invalid; 3798 Value *CallOperandVal = info.CallOperandVal; 3799 // If we don't have a value, we can't do a match, 3800 // but allow it at the lowest weight. 3801 if (!CallOperandVal) 3802 return CW_Default; 3803 Type *type = CallOperandVal->getType(); 3804 // Look at the constraint type. 3805 switch (*constraint) { 3806 default: 3807 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 3808 break; 3809 case 'd': 3810 case 'y': 3811 if (type->isIntegerTy()) 3812 weight = CW_Register; 3813 break; 3814 case 'f': // FPU or MSA register 3815 if (Subtarget.hasMSA() && type->isVectorTy() && 3816 cast<VectorType>(type)->getBitWidth() == 128) 3817 weight = CW_Register; 3818 else if (type->isFloatTy()) 3819 weight = CW_Register; 3820 break; 3821 case 'c': // $25 for indirect jumps 3822 case 'l': // lo register 3823 case 'x': // hilo register pair 3824 if (type->isIntegerTy()) 3825 weight = CW_SpecificReg; 3826 break; 3827 case 'I': // signed 16 bit immediate 3828 case 'J': // integer zero 3829 case 'K': // unsigned 16 bit immediate 3830 case 'L': // signed 32 bit immediate where lower 16 bits are 0 3831 case 'N': // immediate in the range of -65535 to -1 (inclusive) 3832 case 'O': // signed 15 bit immediate (+- 16383) 3833 case 'P': // immediate in the range of 65535 to 1 (inclusive) 3834 if (isa<ConstantInt>(CallOperandVal)) 3835 weight = CW_Constant; 3836 break; 3837 case 'R': 3838 weight = CW_Memory; 3839 break; 3840 } 3841 return weight; 3842 } 3843 3844 /// This is a helper function to parse a physical register string and split it 3845 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag 3846 /// that is returned indicates whether parsing was successful. The second flag 3847 /// is true if the numeric part exists. 3848 static std::pair<bool, bool> parsePhysicalReg(StringRef C, StringRef &Prefix, 3849 unsigned long long &Reg) { 3850 if (C.front() != '{' || C.back() != '}') 3851 return std::make_pair(false, false); 3852 3853 // Search for the first numeric character. 3854 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1; 3855 I = std::find_if(B, E, isdigit); 3856 3857 Prefix = StringRef(B, I - B); 3858 3859 // The second flag is set to false if no numeric characters were found. 3860 if (I == E) 3861 return std::make_pair(true, false); 3862 3863 // Parse the numeric characters. 3864 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg), 3865 true); 3866 } 3867 3868 EVT MipsTargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT, 3869 ISD::NodeType) const { 3870 bool Cond = !Subtarget.isABI_O32() && VT.getSizeInBits() == 32; 3871 EVT MinVT = getRegisterType(Context, Cond ? MVT::i64 : MVT::i32); 3872 return VT.bitsLT(MinVT) ? MinVT : VT; 3873 } 3874 3875 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering:: 3876 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const { 3877 const TargetRegisterInfo *TRI = 3878 Subtarget.getRegisterInfo(); 3879 const TargetRegisterClass *RC; 3880 StringRef Prefix; 3881 unsigned long long Reg; 3882 3883 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg); 3884 3885 if (!R.first) 3886 return std::make_pair(0U, nullptr); 3887 3888 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo. 3889 // No numeric characters follow "hi" or "lo". 3890 if (R.second) 3891 return std::make_pair(0U, nullptr); 3892 3893 RC = TRI->getRegClass(Prefix == "hi" ? 3894 Mips::HI32RegClassID : Mips::LO32RegClassID); 3895 return std::make_pair(*(RC->begin()), RC); 3896 } else if (Prefix.startswith("$msa")) { 3897 // Parse $msa(ir|csr|access|save|modify|request|map|unmap) 3898 3899 // No numeric characters follow the name. 3900 if (R.second) 3901 return std::make_pair(0U, nullptr); 3902 3903 Reg = StringSwitch<unsigned long long>(Prefix) 3904 .Case("$msair", Mips::MSAIR) 3905 .Case("$msacsr", Mips::MSACSR) 3906 .Case("$msaaccess", Mips::MSAAccess) 3907 .Case("$msasave", Mips::MSASave) 3908 .Case("$msamodify", Mips::MSAModify) 3909 .Case("$msarequest", Mips::MSARequest) 3910 .Case("$msamap", Mips::MSAMap) 3911 .Case("$msaunmap", Mips::MSAUnmap) 3912 .Default(0); 3913 3914 if (!Reg) 3915 return std::make_pair(0U, nullptr); 3916 3917 RC = TRI->getRegClass(Mips::MSACtrlRegClassID); 3918 return std::make_pair(Reg, RC); 3919 } 3920 3921 if (!R.second) 3922 return std::make_pair(0U, nullptr); 3923 3924 if (Prefix == "$f") { // Parse $f0-$f31. 3925 // If the size of FP registers is 64-bit or Reg is an even number, select 3926 // the 64-bit register class. Otherwise, select the 32-bit register class. 3927 if (VT == MVT::Other) 3928 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32; 3929 3930 RC = getRegClassFor(VT); 3931 3932 if (RC == &Mips::AFGR64RegClass) { 3933 assert(Reg % 2 == 0); 3934 Reg >>= 1; 3935 } 3936 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7. 3937 RC = TRI->getRegClass(Mips::FCCRegClassID); 3938 else if (Prefix == "$w") { // Parse $w0-$w31. 3939 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT); 3940 } else { // Parse $0-$31. 3941 assert(Prefix == "$"); 3942 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT); 3943 } 3944 3945 assert(Reg < RC->getNumRegs()); 3946 return std::make_pair(*(RC->begin() + Reg), RC); 3947 } 3948 3949 /// Given a register class constraint, like 'r', if this corresponds directly 3950 /// to an LLVM register class, return a register of 0 and the register class 3951 /// pointer. 3952 std::pair<unsigned, const TargetRegisterClass *> 3953 MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 3954 StringRef Constraint, 3955 MVT VT) const { 3956 if (Constraint.size() == 1) { 3957 switch (Constraint[0]) { 3958 case 'd': // Address register. Same as 'r' unless generating MIPS16 code. 3959 case 'y': // Same as 'r'. Exists for compatibility. 3960 case 'r': 3961 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) { 3962 if (Subtarget.inMips16Mode()) 3963 return std::make_pair(0U, &Mips::CPU16RegsRegClass); 3964 return std::make_pair(0U, &Mips::GPR32RegClass); 3965 } 3966 if (VT == MVT::i64 && !Subtarget.isGP64bit()) 3967 return std::make_pair(0U, &Mips::GPR32RegClass); 3968 if (VT == MVT::i64 && Subtarget.isGP64bit()) 3969 return std::make_pair(0U, &Mips::GPR64RegClass); 3970 // This will generate an error message 3971 return std::make_pair(0U, nullptr); 3972 case 'f': // FPU or MSA register 3973 if (VT == MVT::v16i8) 3974 return std::make_pair(0U, &Mips::MSA128BRegClass); 3975 else if (VT == MVT::v8i16 || VT == MVT::v8f16) 3976 return std::make_pair(0U, &Mips::MSA128HRegClass); 3977 else if (VT == MVT::v4i32 || VT == MVT::v4f32) 3978 return std::make_pair(0U, &Mips::MSA128WRegClass); 3979 else if (VT == MVT::v2i64 || VT == MVT::v2f64) 3980 return std::make_pair(0U, &Mips::MSA128DRegClass); 3981 else if (VT == MVT::f32) 3982 return std::make_pair(0U, &Mips::FGR32RegClass); 3983 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) { 3984 if (Subtarget.isFP64bit()) 3985 return std::make_pair(0U, &Mips::FGR64RegClass); 3986 return std::make_pair(0U, &Mips::AFGR64RegClass); 3987 } 3988 break; 3989 case 'c': // register suitable for indirect jump 3990 if (VT == MVT::i32) 3991 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass); 3992 if (VT == MVT::i64) 3993 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass); 3994 // This will generate an error message 3995 return std::make_pair(0U, nullptr); 3996 case 'l': // use the `lo` register to store values 3997 // that are no bigger than a word 3998 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) 3999 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass); 4000 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass); 4001 case 'x': // use the concatenated `hi` and `lo` registers 4002 // to store doubleword values 4003 // Fixme: Not triggering the use of both hi and low 4004 // This will generate an error message 4005 return std::make_pair(0U, nullptr); 4006 } 4007 } 4008 4009 if (!Constraint.empty()) { 4010 std::pair<unsigned, const TargetRegisterClass *> R; 4011 R = parseRegForInlineAsmConstraint(Constraint, VT); 4012 4013 if (R.second) 4014 return R; 4015 } 4016 4017 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 4018 } 4019 4020 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 4021 /// vector. If it is invalid, don't add anything to Ops. 4022 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 4023 std::string &Constraint, 4024 std::vector<SDValue>&Ops, 4025 SelectionDAG &DAG) const { 4026 SDLoc DL(Op); 4027 SDValue Result; 4028 4029 // Only support length 1 constraints for now. 4030 if (Constraint.length() > 1) return; 4031 4032 char ConstraintLetter = Constraint[0]; 4033 switch (ConstraintLetter) { 4034 default: break; // This will fall through to the generic implementation 4035 case 'I': // Signed 16 bit constant 4036 // If this fails, the parent routine will give an error 4037 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 4038 EVT Type = Op.getValueType(); 4039 int64_t Val = C->getSExtValue(); 4040 if (isInt<16>(Val)) { 4041 Result = DAG.getTargetConstant(Val, DL, Type); 4042 break; 4043 } 4044 } 4045 return; 4046 case 'J': // integer zero 4047 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 4048 EVT Type = Op.getValueType(); 4049 int64_t Val = C->getZExtValue(); 4050 if (Val == 0) { 4051 Result = DAG.getTargetConstant(0, DL, Type); 4052 break; 4053 } 4054 } 4055 return; 4056 case 'K': // unsigned 16 bit immediate 4057 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 4058 EVT Type = Op.getValueType(); 4059 uint64_t Val = (uint64_t)C->getZExtValue(); 4060 if (isUInt<16>(Val)) { 4061 Result = DAG.getTargetConstant(Val, DL, Type); 4062 break; 4063 } 4064 } 4065 return; 4066 case 'L': // signed 32 bit immediate where lower 16 bits are 0 4067 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 4068 EVT Type = Op.getValueType(); 4069 int64_t Val = C->getSExtValue(); 4070 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){ 4071 Result = DAG.getTargetConstant(Val, DL, Type); 4072 break; 4073 } 4074 } 4075 return; 4076 case 'N': // immediate in the range of -65535 to -1 (inclusive) 4077 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 4078 EVT Type = Op.getValueType(); 4079 int64_t Val = C->getSExtValue(); 4080 if ((Val >= -65535) && (Val <= -1)) { 4081 Result = DAG.getTargetConstant(Val, DL, Type); 4082 break; 4083 } 4084 } 4085 return; 4086 case 'O': // signed 15 bit immediate 4087 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 4088 EVT Type = Op.getValueType(); 4089 int64_t Val = C->getSExtValue(); 4090 if ((isInt<15>(Val))) { 4091 Result = DAG.getTargetConstant(Val, DL, Type); 4092 break; 4093 } 4094 } 4095 return; 4096 case 'P': // immediate in the range of 1 to 65535 (inclusive) 4097 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 4098 EVT Type = Op.getValueType(); 4099 int64_t Val = C->getSExtValue(); 4100 if ((Val <= 65535) && (Val >= 1)) { 4101 Result = DAG.getTargetConstant(Val, DL, Type); 4102 break; 4103 } 4104 } 4105 return; 4106 } 4107 4108 if (Result.getNode()) { 4109 Ops.push_back(Result); 4110 return; 4111 } 4112 4113 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 4114 } 4115 4116 bool MipsTargetLowering::isLegalAddressingMode(const DataLayout &DL, 4117 const AddrMode &AM, Type *Ty, 4118 unsigned AS, 4119 Instruction *I) const { 4120 // No global is ever allowed as a base. 4121 if (AM.BaseGV) 4122 return false; 4123 4124 switch (AM.Scale) { 4125 case 0: // "r+i" or just "i", depending on HasBaseReg. 4126 break; 4127 case 1: 4128 if (!AM.HasBaseReg) // allow "r+i". 4129 break; 4130 return false; // disallow "r+r" or "r+r+i". 4131 default: 4132 return false; 4133 } 4134 4135 return true; 4136 } 4137 4138 bool 4139 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 4140 // The Mips target isn't yet aware of offsets. 4141 return false; 4142 } 4143 4144 EVT MipsTargetLowering::getOptimalMemOpType( 4145 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 4146 bool ZeroMemset, bool MemcpyStrSrc, 4147 const AttributeList &FuncAttributes) const { 4148 if (Subtarget.hasMips64()) 4149 return MVT::i64; 4150 4151 return MVT::i32; 4152 } 4153 4154 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 4155 bool ForCodeSize) const { 4156 if (VT != MVT::f32 && VT != MVT::f64) 4157 return false; 4158 if (Imm.isNegZero()) 4159 return false; 4160 return Imm.isZero(); 4161 } 4162 4163 unsigned MipsTargetLowering::getJumpTableEncoding() const { 4164 4165 // FIXME: For space reasons this should be: EK_GPRel32BlockAddress. 4166 if (ABI.IsN64() && isPositionIndependent()) 4167 return MachineJumpTableInfo::EK_GPRel64BlockAddress; 4168 4169 return TargetLowering::getJumpTableEncoding(); 4170 } 4171 4172 bool MipsTargetLowering::useSoftFloat() const { 4173 return Subtarget.useSoftFloat(); 4174 } 4175 4176 void MipsTargetLowering::copyByValRegs( 4177 SDValue Chain, const SDLoc &DL, std::vector<SDValue> &OutChains, 4178 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags, 4179 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg, 4180 unsigned FirstReg, unsigned LastReg, const CCValAssign &VA, 4181 MipsCCState &State) const { 4182 MachineFunction &MF = DAG.getMachineFunction(); 4183 MachineFrameInfo &MFI = MF.getFrameInfo(); 4184 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes(); 4185 unsigned NumRegs = LastReg - FirstReg; 4186 unsigned RegAreaSize = NumRegs * GPRSizeInBytes; 4187 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize); 4188 int FrameObjOffset; 4189 ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs(); 4190 4191 if (RegAreaSize) 4192 FrameObjOffset = 4193 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) - 4194 (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes); 4195 else 4196 FrameObjOffset = VA.getLocMemOffset(); 4197 4198 // Create frame object. 4199 EVT PtrTy = getPointerTy(DAG.getDataLayout()); 4200 // Make the fixed object stored to mutable so that the load instructions 4201 // referencing it have their memory dependencies added. 4202 // Set the frame object as isAliased which clears the underlying objects 4203 // vector in ScheduleDAGInstrs::buildSchedGraph() resulting in addition of all 4204 // stores as dependencies for loads referencing this fixed object. 4205 int FI = MFI.CreateFixedObject(FrameObjSize, FrameObjOffset, false, true); 4206 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 4207 InVals.push_back(FIN); 4208 4209 if (!NumRegs) 4210 return; 4211 4212 // Copy arg registers. 4213 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8); 4214 const TargetRegisterClass *RC = getRegClassFor(RegTy); 4215 4216 for (unsigned I = 0; I < NumRegs; ++I) { 4217 unsigned ArgReg = ByValArgRegs[FirstReg + I]; 4218 unsigned VReg = addLiveIn(MF, ArgReg, RC); 4219 unsigned Offset = I * GPRSizeInBytes; 4220 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN, 4221 DAG.getConstant(Offset, DL, PtrTy)); 4222 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy), 4223 StorePtr, MachinePointerInfo(FuncArg, Offset)); 4224 OutChains.push_back(Store); 4225 } 4226 } 4227 4228 // Copy byVal arg to registers and stack. 4229 void MipsTargetLowering::passByValArg( 4230 SDValue Chain, const SDLoc &DL, 4231 std::deque<std::pair<unsigned, SDValue>> &RegsToPass, 4232 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr, 4233 MachineFrameInfo &MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg, 4234 unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle, 4235 const CCValAssign &VA) const { 4236 unsigned ByValSizeInBytes = Flags.getByValSize(); 4237 unsigned OffsetInBytes = 0; // From beginning of struct 4238 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes(); 4239 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes); 4240 EVT PtrTy = getPointerTy(DAG.getDataLayout()), 4241 RegTy = MVT::getIntegerVT(RegSizeInBytes * 8); 4242 unsigned NumRegs = LastReg - FirstReg; 4243 4244 if (NumRegs) { 4245 ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs(); 4246 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes); 4247 unsigned I = 0; 4248 4249 // Copy words to registers. 4250 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) { 4251 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg, 4252 DAG.getConstant(OffsetInBytes, DL, PtrTy)); 4253 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr, 4254 MachinePointerInfo(), Alignment); 4255 MemOpChains.push_back(LoadVal.getValue(1)); 4256 unsigned ArgReg = ArgRegs[FirstReg + I]; 4257 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal)); 4258 } 4259 4260 // Return if the struct has been fully copied. 4261 if (ByValSizeInBytes == OffsetInBytes) 4262 return; 4263 4264 // Copy the remainder of the byval argument with sub-word loads and shifts. 4265 if (LeftoverBytes) { 4266 SDValue Val; 4267 4268 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0; 4269 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) { 4270 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes; 4271 4272 if (RemainingSizeInBytes < LoadSizeInBytes) 4273 continue; 4274 4275 // Load subword. 4276 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg, 4277 DAG.getConstant(OffsetInBytes, DL, 4278 PtrTy)); 4279 SDValue LoadVal = DAG.getExtLoad( 4280 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(), 4281 MVT::getIntegerVT(LoadSizeInBytes * 8), Alignment); 4282 MemOpChains.push_back(LoadVal.getValue(1)); 4283 4284 // Shift the loaded value. 4285 unsigned Shamt; 4286 4287 if (isLittle) 4288 Shamt = TotalBytesLoaded * 8; 4289 else 4290 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8; 4291 4292 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal, 4293 DAG.getConstant(Shamt, DL, MVT::i32)); 4294 4295 if (Val.getNode()) 4296 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift); 4297 else 4298 Val = Shift; 4299 4300 OffsetInBytes += LoadSizeInBytes; 4301 TotalBytesLoaded += LoadSizeInBytes; 4302 Alignment = std::min(Alignment, LoadSizeInBytes); 4303 } 4304 4305 unsigned ArgReg = ArgRegs[FirstReg + I]; 4306 RegsToPass.push_back(std::make_pair(ArgReg, Val)); 4307 return; 4308 } 4309 } 4310 4311 // Copy remainder of byval arg to it with memcpy. 4312 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes; 4313 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg, 4314 DAG.getConstant(OffsetInBytes, DL, PtrTy)); 4315 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr, 4316 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 4317 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, 4318 DAG.getConstant(MemCpySize, DL, PtrTy), 4319 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false, 4320 /*isTailCall=*/false, 4321 MachinePointerInfo(), MachinePointerInfo()); 4322 MemOpChains.push_back(Chain); 4323 } 4324 4325 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains, 4326 SDValue Chain, const SDLoc &DL, 4327 SelectionDAG &DAG, 4328 CCState &State) const { 4329 ArrayRef<MCPhysReg> ArgRegs = ABI.GetVarArgRegs(); 4330 unsigned Idx = State.getFirstUnallocated(ArgRegs); 4331 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes(); 4332 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8); 4333 const TargetRegisterClass *RC = getRegClassFor(RegTy); 4334 MachineFunction &MF = DAG.getMachineFunction(); 4335 MachineFrameInfo &MFI = MF.getFrameInfo(); 4336 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>(); 4337 4338 // Offset of the first variable argument from stack pointer. 4339 int VaArgOffset; 4340 4341 if (ArgRegs.size() == Idx) 4342 VaArgOffset = alignTo(State.getNextStackOffset(), RegSizeInBytes); 4343 else { 4344 VaArgOffset = 4345 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) - 4346 (int)(RegSizeInBytes * (ArgRegs.size() - Idx)); 4347 } 4348 4349 // Record the frame index of the first variable argument 4350 // which is a value necessary to VASTART. 4351 int FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true); 4352 MipsFI->setVarArgsFrameIndex(FI); 4353 4354 // Copy the integer registers that have not been used for argument passing 4355 // to the argument register save area. For O32, the save area is allocated 4356 // in the caller's stack frame, while for N32/64, it is allocated in the 4357 // callee's stack frame. 4358 for (unsigned I = Idx; I < ArgRegs.size(); 4359 ++I, VaArgOffset += RegSizeInBytes) { 4360 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC); 4361 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy); 4362 FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true); 4363 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 4364 SDValue Store = 4365 DAG.getStore(Chain, DL, ArgValue, PtrOff, MachinePointerInfo()); 4366 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue( 4367 (Value *)nullptr); 4368 OutChains.push_back(Store); 4369 } 4370 } 4371 4372 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size, 4373 unsigned Align) const { 4374 const TargetFrameLowering *TFL = Subtarget.getFrameLowering(); 4375 4376 assert(Size && "Byval argument's size shouldn't be 0."); 4377 4378 Align = std::min(Align, TFL->getStackAlignment()); 4379 4380 unsigned FirstReg = 0; 4381 unsigned NumRegs = 0; 4382 4383 if (State->getCallingConv() != CallingConv::Fast) { 4384 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes(); 4385 ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs(); 4386 // FIXME: The O32 case actually describes no shadow registers. 4387 const MCPhysReg *ShadowRegs = 4388 ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs; 4389 4390 // We used to check the size as well but we can't do that anymore since 4391 // CCState::HandleByVal() rounds up the size after calling this function. 4392 assert(!(Align % RegSizeInBytes) && 4393 "Byval argument's alignment should be a multiple of" 4394 "RegSizeInBytes."); 4395 4396 FirstReg = State->getFirstUnallocated(IntArgRegs); 4397 4398 // If Align > RegSizeInBytes, the first arg register must be even. 4399 // FIXME: This condition happens to do the right thing but it's not the 4400 // right way to test it. We want to check that the stack frame offset 4401 // of the register is aligned. 4402 if ((Align > RegSizeInBytes) && (FirstReg % 2)) { 4403 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]); 4404 ++FirstReg; 4405 } 4406 4407 // Mark the registers allocated. 4408 Size = alignTo(Size, RegSizeInBytes); 4409 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size()); 4410 Size -= RegSizeInBytes, ++I, ++NumRegs) 4411 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]); 4412 } 4413 4414 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs); 4415 } 4416 4417 MachineBasicBlock *MipsTargetLowering::emitPseudoSELECT(MachineInstr &MI, 4418 MachineBasicBlock *BB, 4419 bool isFPCmp, 4420 unsigned Opc) const { 4421 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) && 4422 "Subtarget already supports SELECT nodes with the use of" 4423 "conditional-move instructions."); 4424 4425 const TargetInstrInfo *TII = 4426 Subtarget.getInstrInfo(); 4427 DebugLoc DL = MI.getDebugLoc(); 4428 4429 // To "insert" a SELECT instruction, we actually have to insert the 4430 // diamond control-flow pattern. The incoming instruction knows the 4431 // destination vreg to set, the condition code register to branch on, the 4432 // true/false values to select between, and a branch opcode to use. 4433 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 4434 MachineFunction::iterator It = ++BB->getIterator(); 4435 4436 // thisMBB: 4437 // ... 4438 // TrueVal = ... 4439 // setcc r1, r2, r3 4440 // bNE r1, r0, copy1MBB 4441 // fallthrough --> copy0MBB 4442 MachineBasicBlock *thisMBB = BB; 4443 MachineFunction *F = BB->getParent(); 4444 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 4445 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 4446 F->insert(It, copy0MBB); 4447 F->insert(It, sinkMBB); 4448 4449 // Transfer the remainder of BB and its successor edges to sinkMBB. 4450 sinkMBB->splice(sinkMBB->begin(), BB, 4451 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 4452 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 4453 4454 // Next, add the true and fallthrough blocks as its successors. 4455 BB->addSuccessor(copy0MBB); 4456 BB->addSuccessor(sinkMBB); 4457 4458 if (isFPCmp) { 4459 // bc1[tf] cc, sinkMBB 4460 BuildMI(BB, DL, TII->get(Opc)) 4461 .addReg(MI.getOperand(1).getReg()) 4462 .addMBB(sinkMBB); 4463 } else { 4464 // bne rs, $0, sinkMBB 4465 BuildMI(BB, DL, TII->get(Opc)) 4466 .addReg(MI.getOperand(1).getReg()) 4467 .addReg(Mips::ZERO) 4468 .addMBB(sinkMBB); 4469 } 4470 4471 // copy0MBB: 4472 // %FalseValue = ... 4473 // # fallthrough to sinkMBB 4474 BB = copy0MBB; 4475 4476 // Update machine-CFG edges 4477 BB->addSuccessor(sinkMBB); 4478 4479 // sinkMBB: 4480 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ] 4481 // ... 4482 BB = sinkMBB; 4483 4484 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(0).getReg()) 4485 .addReg(MI.getOperand(2).getReg()) 4486 .addMBB(thisMBB) 4487 .addReg(MI.getOperand(3).getReg()) 4488 .addMBB(copy0MBB); 4489 4490 MI.eraseFromParent(); // The pseudo instruction is gone now. 4491 4492 return BB; 4493 } 4494 4495 MachineBasicBlock * 4496 MipsTargetLowering::emitPseudoD_SELECT(MachineInstr &MI, 4497 MachineBasicBlock *BB) const { 4498 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) && 4499 "Subtarget already supports SELECT nodes with the use of" 4500 "conditional-move instructions."); 4501 4502 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 4503 DebugLoc DL = MI.getDebugLoc(); 4504 4505 // D_SELECT substitutes two SELECT nodes that goes one after another and 4506 // have the same condition operand. On machines which don't have 4507 // conditional-move instruction, it reduces unnecessary branch instructions 4508 // which are result of using two diamond patterns that are result of two 4509 // SELECT pseudo instructions. 4510 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 4511 MachineFunction::iterator It = ++BB->getIterator(); 4512 4513 // thisMBB: 4514 // ... 4515 // TrueVal = ... 4516 // setcc r1, r2, r3 4517 // bNE r1, r0, copy1MBB 4518 // fallthrough --> copy0MBB 4519 MachineBasicBlock *thisMBB = BB; 4520 MachineFunction *F = BB->getParent(); 4521 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 4522 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 4523 F->insert(It, copy0MBB); 4524 F->insert(It, sinkMBB); 4525 4526 // Transfer the remainder of BB and its successor edges to sinkMBB. 4527 sinkMBB->splice(sinkMBB->begin(), BB, 4528 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 4529 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 4530 4531 // Next, add the true and fallthrough blocks as its successors. 4532 BB->addSuccessor(copy0MBB); 4533 BB->addSuccessor(sinkMBB); 4534 4535 // bne rs, $0, sinkMBB 4536 BuildMI(BB, DL, TII->get(Mips::BNE)) 4537 .addReg(MI.getOperand(2).getReg()) 4538 .addReg(Mips::ZERO) 4539 .addMBB(sinkMBB); 4540 4541 // copy0MBB: 4542 // %FalseValue = ... 4543 // # fallthrough to sinkMBB 4544 BB = copy0MBB; 4545 4546 // Update machine-CFG edges 4547 BB->addSuccessor(sinkMBB); 4548 4549 // sinkMBB: 4550 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ] 4551 // ... 4552 BB = sinkMBB; 4553 4554 // Use two PHI nodes to select two reults 4555 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(0).getReg()) 4556 .addReg(MI.getOperand(3).getReg()) 4557 .addMBB(thisMBB) 4558 .addReg(MI.getOperand(5).getReg()) 4559 .addMBB(copy0MBB); 4560 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(1).getReg()) 4561 .addReg(MI.getOperand(4).getReg()) 4562 .addMBB(thisMBB) 4563 .addReg(MI.getOperand(6).getReg()) 4564 .addMBB(copy0MBB); 4565 4566 MI.eraseFromParent(); // The pseudo instruction is gone now. 4567 4568 return BB; 4569 } 4570 4571 // FIXME? Maybe this could be a TableGen attribute on some registers and 4572 // this table could be generated automatically from RegInfo. 4573 Register 4574 MipsTargetLowering::getRegisterByName(const char *RegName, EVT VT, 4575 const MachineFunction &MF) const { 4576 // Named registers is expected to be fairly rare. For now, just support $28 4577 // since the linux kernel uses it. 4578 if (Subtarget.isGP64bit()) { 4579 Register Reg = StringSwitch<Register>(RegName) 4580 .Case("$28", Mips::GP_64) 4581 .Default(Register()); 4582 if (Reg) 4583 return Reg; 4584 } else { 4585 Register Reg = StringSwitch<Register>(RegName) 4586 .Case("$28", Mips::GP) 4587 .Default(Register()); 4588 if (Reg) 4589 return Reg; 4590 } 4591 report_fatal_error("Invalid register name global variable"); 4592 } 4593