1 //===-- BPFISelLowering.cpp - BPF 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 BPF uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "BPFISelLowering.h" 15 #include "BPF.h" 16 #include "BPFSubtarget.h" 17 #include "BPFTargetMachine.h" 18 #include "llvm/CodeGen/CallingConvLower.h" 19 #include "llvm/CodeGen/MachineFrameInfo.h" 20 #include "llvm/CodeGen/MachineFunction.h" 21 #include "llvm/CodeGen/MachineInstrBuilder.h" 22 #include "llvm/CodeGen/MachineRegisterInfo.h" 23 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 24 #include "llvm/CodeGen/ValueTypes.h" 25 #include "llvm/IR/DiagnosticInfo.h" 26 #include "llvm/IR/DiagnosticPrinter.h" 27 #include "llvm/Support/Debug.h" 28 #include "llvm/Support/ErrorHandling.h" 29 #include "llvm/Support/raw_ostream.h" 30 using namespace llvm; 31 32 #define DEBUG_TYPE "bpf-lower" 33 34 static cl::opt<bool> BPFExpandMemcpyInOrder("bpf-expand-memcpy-in-order", 35 cl::Hidden, cl::init(false), 36 cl::desc("Expand memcpy into load/store pairs in order")); 37 38 static void fail(const SDLoc &DL, SelectionDAG &DAG, const Twine &Msg) { 39 MachineFunction &MF = DAG.getMachineFunction(); 40 DAG.getContext()->diagnose( 41 DiagnosticInfoUnsupported(MF.getFunction(), Msg, DL.getDebugLoc())); 42 } 43 44 static void fail(const SDLoc &DL, SelectionDAG &DAG, const char *Msg, 45 SDValue Val) { 46 MachineFunction &MF = DAG.getMachineFunction(); 47 std::string Str; 48 raw_string_ostream OS(Str); 49 OS << Msg; 50 Val->print(OS); 51 OS.flush(); 52 DAG.getContext()->diagnose( 53 DiagnosticInfoUnsupported(MF.getFunction(), Str, DL.getDebugLoc())); 54 } 55 56 BPFTargetLowering::BPFTargetLowering(const TargetMachine &TM, 57 const BPFSubtarget &STI) 58 : TargetLowering(TM) { 59 60 // Set up the register classes. 61 addRegisterClass(MVT::i64, &BPF::GPRRegClass); 62 if (STI.getHasAlu32()) 63 addRegisterClass(MVT::i32, &BPF::GPR32RegClass); 64 65 // Compute derived properties from the register classes 66 computeRegisterProperties(STI.getRegisterInfo()); 67 68 setStackPointerRegisterToSaveRestore(BPF::R11); 69 70 setOperationAction(ISD::BR_CC, MVT::i64, Custom); 71 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 72 setOperationAction(ISD::BRIND, MVT::Other, Expand); 73 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 74 75 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 76 77 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom); 78 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 79 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 80 81 // Set unsupported atomic operations as Custom so 82 // we can emit better error messages than fatal error 83 // from selectiondag. 84 for (auto VT : {MVT::i8, MVT::i16, MVT::i32}) { 85 if (VT == MVT::i32) { 86 if (STI.getHasAlu32()) 87 continue; 88 } else { 89 setOperationAction(ISD::ATOMIC_LOAD_ADD, VT, Custom); 90 } 91 92 setOperationAction(ISD::ATOMIC_LOAD_AND, VT, Custom); 93 setOperationAction(ISD::ATOMIC_LOAD_OR, VT, Custom); 94 setOperationAction(ISD::ATOMIC_LOAD_XOR, VT, Custom); 95 setOperationAction(ISD::ATOMIC_SWAP, VT, Custom); 96 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom); 97 } 98 99 for (auto VT : { MVT::i32, MVT::i64 }) { 100 if (VT == MVT::i32 && !STI.getHasAlu32()) 101 continue; 102 103 setOperationAction(ISD::SDIVREM, VT, Expand); 104 setOperationAction(ISD::UDIVREM, VT, Expand); 105 setOperationAction(ISD::SREM, VT, Expand); 106 setOperationAction(ISD::UREM, VT, Expand); 107 setOperationAction(ISD::MULHU, VT, Expand); 108 setOperationAction(ISD::MULHS, VT, Expand); 109 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 110 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 111 setOperationAction(ISD::ROTR, VT, Expand); 112 setOperationAction(ISD::ROTL, VT, Expand); 113 setOperationAction(ISD::SHL_PARTS, VT, Expand); 114 setOperationAction(ISD::SRL_PARTS, VT, Expand); 115 setOperationAction(ISD::SRA_PARTS, VT, Expand); 116 setOperationAction(ISD::CTPOP, VT, Expand); 117 118 setOperationAction(ISD::SETCC, VT, Expand); 119 setOperationAction(ISD::SELECT, VT, Expand); 120 setOperationAction(ISD::SELECT_CC, VT, Custom); 121 } 122 123 if (STI.getHasAlu32()) { 124 setOperationAction(ISD::BSWAP, MVT::i32, Promote); 125 setOperationAction(ISD::BR_CC, MVT::i32, 126 STI.getHasJmp32() ? Custom : Promote); 127 } 128 129 setOperationAction(ISD::CTTZ, MVT::i64, Custom); 130 setOperationAction(ISD::CTLZ, MVT::i64, Custom); 131 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Custom); 132 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom); 133 134 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 135 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 136 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 137 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Expand); 138 139 // Extended load operations for i1 types must be promoted 140 for (MVT VT : MVT::integer_valuetypes()) { 141 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote); 142 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 143 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 144 145 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 146 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Expand); 147 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand); 148 } 149 150 setBooleanContents(ZeroOrOneBooleanContent); 151 152 // Function alignments 153 setMinFunctionAlignment(Align(8)); 154 setPrefFunctionAlignment(Align(8)); 155 156 if (BPFExpandMemcpyInOrder) { 157 // LLVM generic code will try to expand memcpy into load/store pairs at this 158 // stage which is before quite a few IR optimization passes, therefore the 159 // loads and stores could potentially be moved apart from each other which 160 // will cause trouble to memcpy pattern matcher inside kernel eBPF JIT 161 // compilers. 162 // 163 // When -bpf-expand-memcpy-in-order specified, we want to defer the expand 164 // of memcpy to later stage in IR optimization pipeline so those load/store 165 // pairs won't be touched and could be kept in order. Hence, we set 166 // MaxStoresPerMem* to zero to disable the generic getMemcpyLoadsAndStores 167 // code path, and ask LLVM to use target expander EmitTargetCodeForMemcpy. 168 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 0; 169 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 0; 170 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 0; 171 MaxLoadsPerMemcmp = 0; 172 } else { 173 // inline memcpy() for kernel to see explicit copy 174 unsigned CommonMaxStores = 175 STI.getSelectionDAGInfo()->getCommonMaxStoresPerMemFunc(); 176 177 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = CommonMaxStores; 178 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = CommonMaxStores; 179 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = CommonMaxStores; 180 MaxLoadsPerMemcmp = MaxLoadsPerMemcmpOptSize = CommonMaxStores; 181 } 182 183 // CPU/Feature control 184 HasAlu32 = STI.getHasAlu32(); 185 HasJmp32 = STI.getHasJmp32(); 186 HasJmpExt = STI.getHasJmpExt(); 187 } 188 189 bool BPFTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 190 return false; 191 } 192 193 bool BPFTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 194 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 195 return false; 196 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 197 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 198 return NumBits1 > NumBits2; 199 } 200 201 bool BPFTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 202 if (!VT1.isInteger() || !VT2.isInteger()) 203 return false; 204 unsigned NumBits1 = VT1.getSizeInBits(); 205 unsigned NumBits2 = VT2.getSizeInBits(); 206 return NumBits1 > NumBits2; 207 } 208 209 bool BPFTargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { 210 if (!getHasAlu32() || !Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 211 return false; 212 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 213 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 214 return NumBits1 == 32 && NumBits2 == 64; 215 } 216 217 bool BPFTargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 218 if (!getHasAlu32() || !VT1.isInteger() || !VT2.isInteger()) 219 return false; 220 unsigned NumBits1 = VT1.getSizeInBits(); 221 unsigned NumBits2 = VT2.getSizeInBits(); 222 return NumBits1 == 32 && NumBits2 == 64; 223 } 224 225 BPFTargetLowering::ConstraintType 226 BPFTargetLowering::getConstraintType(StringRef Constraint) const { 227 if (Constraint.size() == 1) { 228 switch (Constraint[0]) { 229 default: 230 break; 231 case 'w': 232 return C_RegisterClass; 233 } 234 } 235 236 return TargetLowering::getConstraintType(Constraint); 237 } 238 239 std::pair<unsigned, const TargetRegisterClass *> 240 BPFTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 241 StringRef Constraint, 242 MVT VT) const { 243 if (Constraint.size() == 1) 244 // GCC Constraint Letters 245 switch (Constraint[0]) { 246 case 'r': // GENERAL_REGS 247 return std::make_pair(0U, &BPF::GPRRegClass); 248 case 'w': 249 if (HasAlu32) 250 return std::make_pair(0U, &BPF::GPR32RegClass); 251 break; 252 default: 253 break; 254 } 255 256 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 257 } 258 259 void BPFTargetLowering::ReplaceNodeResults( 260 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const { 261 const char *err_msg; 262 uint32_t Opcode = N->getOpcode(); 263 switch (Opcode) { 264 default: 265 report_fatal_error("Unhandled custom legalization"); 266 case ISD::ATOMIC_LOAD_ADD: 267 case ISD::ATOMIC_LOAD_AND: 268 case ISD::ATOMIC_LOAD_OR: 269 case ISD::ATOMIC_LOAD_XOR: 270 case ISD::ATOMIC_SWAP: 271 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 272 if (HasAlu32 || Opcode == ISD::ATOMIC_LOAD_ADD) 273 err_msg = "Unsupported atomic operations, please use 32/64 bit version"; 274 else 275 err_msg = "Unsupported atomic operations, please use 64 bit version"; 276 break; 277 } 278 279 SDLoc DL(N); 280 fail(DL, DAG, err_msg); 281 } 282 283 SDValue BPFTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 284 switch (Op.getOpcode()) { 285 case ISD::BR_CC: 286 return LowerBR_CC(Op, DAG); 287 case ISD::GlobalAddress: 288 return LowerGlobalAddress(Op, DAG); 289 case ISD::SELECT_CC: 290 return LowerSELECT_CC(Op, DAG); 291 case ISD::DYNAMIC_STACKALLOC: 292 report_fatal_error("Unsupported dynamic stack allocation"); 293 default: 294 llvm_unreachable("unimplemented operand"); 295 } 296 } 297 298 // Calling Convention Implementation 299 #include "BPFGenCallingConv.inc" 300 301 SDValue BPFTargetLowering::LowerFormalArguments( 302 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 303 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 304 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 305 switch (CallConv) { 306 default: 307 report_fatal_error("Unsupported calling convention"); 308 case CallingConv::C: 309 case CallingConv::Fast: 310 break; 311 } 312 313 MachineFunction &MF = DAG.getMachineFunction(); 314 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 315 316 // Assign locations to all of the incoming arguments. 317 SmallVector<CCValAssign, 16> ArgLocs; 318 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 319 CCInfo.AnalyzeFormalArguments(Ins, getHasAlu32() ? CC_BPF32 : CC_BPF64); 320 321 for (auto &VA : ArgLocs) { 322 if (VA.isRegLoc()) { 323 // Arguments passed in registers 324 EVT RegVT = VA.getLocVT(); 325 MVT::SimpleValueType SimpleTy = RegVT.getSimpleVT().SimpleTy; 326 switch (SimpleTy) { 327 default: { 328 errs() << "LowerFormalArguments Unhandled argument type: " 329 << RegVT.getEVTString() << '\n'; 330 llvm_unreachable(nullptr); 331 } 332 case MVT::i32: 333 case MVT::i64: 334 Register VReg = RegInfo.createVirtualRegister( 335 SimpleTy == MVT::i64 ? &BPF::GPRRegClass : &BPF::GPR32RegClass); 336 RegInfo.addLiveIn(VA.getLocReg(), VReg); 337 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, RegVT); 338 339 // If this is an value that has been promoted to wider types, insert an 340 // assert[sz]ext to capture this, then truncate to the right size. 341 if (VA.getLocInfo() == CCValAssign::SExt) 342 ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue, 343 DAG.getValueType(VA.getValVT())); 344 else if (VA.getLocInfo() == CCValAssign::ZExt) 345 ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue, 346 DAG.getValueType(VA.getValVT())); 347 348 if (VA.getLocInfo() != CCValAssign::Full) 349 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue); 350 351 InVals.push_back(ArgValue); 352 353 break; 354 } 355 } else { 356 fail(DL, DAG, "defined with too many args"); 357 InVals.push_back(DAG.getConstant(0, DL, VA.getLocVT())); 358 } 359 } 360 361 if (IsVarArg || MF.getFunction().hasStructRetAttr()) { 362 fail(DL, DAG, "functions with VarArgs or StructRet are not supported"); 363 } 364 365 return Chain; 366 } 367 368 const unsigned BPFTargetLowering::MaxArgs = 5; 369 370 SDValue BPFTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 371 SmallVectorImpl<SDValue> &InVals) const { 372 SelectionDAG &DAG = CLI.DAG; 373 auto &Outs = CLI.Outs; 374 auto &OutVals = CLI.OutVals; 375 auto &Ins = CLI.Ins; 376 SDValue Chain = CLI.Chain; 377 SDValue Callee = CLI.Callee; 378 bool &IsTailCall = CLI.IsTailCall; 379 CallingConv::ID CallConv = CLI.CallConv; 380 bool IsVarArg = CLI.IsVarArg; 381 MachineFunction &MF = DAG.getMachineFunction(); 382 383 // BPF target does not support tail call optimization. 384 IsTailCall = false; 385 386 switch (CallConv) { 387 default: 388 report_fatal_error("Unsupported calling convention"); 389 case CallingConv::Fast: 390 case CallingConv::C: 391 break; 392 } 393 394 // Analyze operands of the call, assigning locations to each operand. 395 SmallVector<CCValAssign, 16> ArgLocs; 396 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 397 398 CCInfo.AnalyzeCallOperands(Outs, getHasAlu32() ? CC_BPF32 : CC_BPF64); 399 400 unsigned NumBytes = CCInfo.getNextStackOffset(); 401 402 if (Outs.size() > MaxArgs) 403 fail(CLI.DL, DAG, "too many args to ", Callee); 404 405 for (auto &Arg : Outs) { 406 ISD::ArgFlagsTy Flags = Arg.Flags; 407 if (!Flags.isByVal()) 408 continue; 409 410 fail(CLI.DL, DAG, "pass by value not supported ", Callee); 411 } 412 413 auto PtrVT = getPointerTy(MF.getDataLayout()); 414 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 415 416 SmallVector<std::pair<unsigned, SDValue>, MaxArgs> RegsToPass; 417 418 // Walk arg assignments 419 for (unsigned i = 0, 420 e = std::min(static_cast<unsigned>(ArgLocs.size()), MaxArgs); 421 i != e; ++i) { 422 CCValAssign &VA = ArgLocs[i]; 423 SDValue Arg = OutVals[i]; 424 425 // Promote the value if needed. 426 switch (VA.getLocInfo()) { 427 default: 428 llvm_unreachable("Unknown loc info"); 429 case CCValAssign::Full: 430 break; 431 case CCValAssign::SExt: 432 Arg = DAG.getNode(ISD::SIGN_EXTEND, CLI.DL, VA.getLocVT(), Arg); 433 break; 434 case CCValAssign::ZExt: 435 Arg = DAG.getNode(ISD::ZERO_EXTEND, CLI.DL, VA.getLocVT(), Arg); 436 break; 437 case CCValAssign::AExt: 438 Arg = DAG.getNode(ISD::ANY_EXTEND, CLI.DL, VA.getLocVT(), Arg); 439 break; 440 } 441 442 // Push arguments into RegsToPass vector 443 if (VA.isRegLoc()) 444 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 445 else 446 llvm_unreachable("call arg pass bug"); 447 } 448 449 SDValue InFlag; 450 451 // Build a sequence of copy-to-reg nodes chained together with token chain and 452 // flag operands which copy the outgoing args into registers. The InFlag in 453 // necessary since all emitted instructions must be stuck together. 454 for (auto &Reg : RegsToPass) { 455 Chain = DAG.getCopyToReg(Chain, CLI.DL, Reg.first, Reg.second, InFlag); 456 InFlag = Chain.getValue(1); 457 } 458 459 // If the callee is a GlobalAddress node (quite common, every direct call is) 460 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it. 461 // Likewise ExternalSymbol -> TargetExternalSymbol. 462 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 463 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), CLI.DL, PtrVT, 464 G->getOffset(), 0); 465 } else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee)) { 466 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT, 0); 467 fail(CLI.DL, DAG, Twine("A call to built-in function '" 468 + StringRef(E->getSymbol()) 469 + "' is not supported.")); 470 } 471 472 // Returns a chain & a flag for retval copy to use. 473 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 474 SmallVector<SDValue, 8> Ops; 475 Ops.push_back(Chain); 476 Ops.push_back(Callee); 477 478 // Add argument registers to the end of the list so that they are 479 // known live into the call. 480 for (auto &Reg : RegsToPass) 481 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 482 483 if (InFlag.getNode()) 484 Ops.push_back(InFlag); 485 486 Chain = DAG.getNode(BPFISD::CALL, CLI.DL, NodeTys, Ops); 487 InFlag = Chain.getValue(1); 488 489 // Create the CALLSEQ_END node. 490 Chain = DAG.getCALLSEQ_END( 491 Chain, DAG.getConstant(NumBytes, CLI.DL, PtrVT, true), 492 DAG.getConstant(0, CLI.DL, PtrVT, true), InFlag, CLI.DL); 493 InFlag = Chain.getValue(1); 494 495 // Handle result values, copying them out of physregs into vregs that we 496 // return. 497 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, CLI.DL, DAG, 498 InVals); 499 } 500 501 SDValue 502 BPFTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 503 bool IsVarArg, 504 const SmallVectorImpl<ISD::OutputArg> &Outs, 505 const SmallVectorImpl<SDValue> &OutVals, 506 const SDLoc &DL, SelectionDAG &DAG) const { 507 unsigned Opc = BPFISD::RET_FLAG; 508 509 // CCValAssign - represent the assignment of the return value to a location 510 SmallVector<CCValAssign, 16> RVLocs; 511 MachineFunction &MF = DAG.getMachineFunction(); 512 513 // CCState - Info about the registers and stack slot. 514 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 515 516 if (MF.getFunction().getReturnType()->isAggregateType()) { 517 fail(DL, DAG, "only integer returns supported"); 518 return DAG.getNode(Opc, DL, MVT::Other, Chain); 519 } 520 521 // Analize return values. 522 CCInfo.AnalyzeReturn(Outs, getHasAlu32() ? RetCC_BPF32 : RetCC_BPF64); 523 524 SDValue Flag; 525 SmallVector<SDValue, 4> RetOps(1, Chain); 526 527 // Copy the result values into the output registers. 528 for (unsigned i = 0; i != RVLocs.size(); ++i) { 529 CCValAssign &VA = RVLocs[i]; 530 assert(VA.isRegLoc() && "Can only return in registers!"); 531 532 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), OutVals[i], Flag); 533 534 // Guarantee that all emitted copies are stuck together, 535 // avoiding something bad. 536 Flag = Chain.getValue(1); 537 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 538 } 539 540 RetOps[0] = Chain; // Update chain. 541 542 // Add the flag if we have it. 543 if (Flag.getNode()) 544 RetOps.push_back(Flag); 545 546 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 547 } 548 549 SDValue BPFTargetLowering::LowerCallResult( 550 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 551 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 552 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 553 554 MachineFunction &MF = DAG.getMachineFunction(); 555 // Assign locations to each value returned by this call. 556 SmallVector<CCValAssign, 16> RVLocs; 557 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 558 559 if (Ins.size() >= 2) { 560 fail(DL, DAG, "only small returns supported"); 561 for (unsigned i = 0, e = Ins.size(); i != e; ++i) 562 InVals.push_back(DAG.getConstant(0, DL, Ins[i].VT)); 563 return DAG.getCopyFromReg(Chain, DL, 1, Ins[0].VT, InFlag).getValue(1); 564 } 565 566 CCInfo.AnalyzeCallResult(Ins, getHasAlu32() ? RetCC_BPF32 : RetCC_BPF64); 567 568 // Copy all of the result registers out of their specified physreg. 569 for (auto &Val : RVLocs) { 570 Chain = DAG.getCopyFromReg(Chain, DL, Val.getLocReg(), 571 Val.getValVT(), InFlag).getValue(1); 572 InFlag = Chain.getValue(2); 573 InVals.push_back(Chain.getValue(0)); 574 } 575 576 return Chain; 577 } 578 579 static void NegateCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) { 580 switch (CC) { 581 default: 582 break; 583 case ISD::SETULT: 584 case ISD::SETULE: 585 case ISD::SETLT: 586 case ISD::SETLE: 587 CC = ISD::getSetCCSwappedOperands(CC); 588 std::swap(LHS, RHS); 589 break; 590 } 591 } 592 593 SDValue BPFTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 594 SDValue Chain = Op.getOperand(0); 595 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 596 SDValue LHS = Op.getOperand(2); 597 SDValue RHS = Op.getOperand(3); 598 SDValue Dest = Op.getOperand(4); 599 SDLoc DL(Op); 600 601 if (!getHasJmpExt()) 602 NegateCC(LHS, RHS, CC); 603 604 return DAG.getNode(BPFISD::BR_CC, DL, Op.getValueType(), Chain, LHS, RHS, 605 DAG.getConstant(CC, DL, LHS.getValueType()), Dest); 606 } 607 608 SDValue BPFTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 609 SDValue LHS = Op.getOperand(0); 610 SDValue RHS = Op.getOperand(1); 611 SDValue TrueV = Op.getOperand(2); 612 SDValue FalseV = Op.getOperand(3); 613 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 614 SDLoc DL(Op); 615 616 if (!getHasJmpExt()) 617 NegateCC(LHS, RHS, CC); 618 619 SDValue TargetCC = DAG.getConstant(CC, DL, LHS.getValueType()); 620 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue); 621 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 622 623 return DAG.getNode(BPFISD::SELECT_CC, DL, VTs, Ops); 624 } 625 626 const char *BPFTargetLowering::getTargetNodeName(unsigned Opcode) const { 627 switch ((BPFISD::NodeType)Opcode) { 628 case BPFISD::FIRST_NUMBER: 629 break; 630 case BPFISD::RET_FLAG: 631 return "BPFISD::RET_FLAG"; 632 case BPFISD::CALL: 633 return "BPFISD::CALL"; 634 case BPFISD::SELECT_CC: 635 return "BPFISD::SELECT_CC"; 636 case BPFISD::BR_CC: 637 return "BPFISD::BR_CC"; 638 case BPFISD::Wrapper: 639 return "BPFISD::Wrapper"; 640 case BPFISD::MEMCPY: 641 return "BPFISD::MEMCPY"; 642 } 643 return nullptr; 644 } 645 646 SDValue BPFTargetLowering::LowerGlobalAddress(SDValue Op, 647 SelectionDAG &DAG) const { 648 auto N = cast<GlobalAddressSDNode>(Op); 649 assert(N->getOffset() == 0 && "Invalid offset for global address"); 650 651 SDLoc DL(Op); 652 const GlobalValue *GV = N->getGlobal(); 653 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i64); 654 655 return DAG.getNode(BPFISD::Wrapper, DL, MVT::i64, GA); 656 } 657 658 unsigned 659 BPFTargetLowering::EmitSubregExt(MachineInstr &MI, MachineBasicBlock *BB, 660 unsigned Reg, bool isSigned) const { 661 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 662 const TargetRegisterClass *RC = getRegClassFor(MVT::i64); 663 int RShiftOp = isSigned ? BPF::SRA_ri : BPF::SRL_ri; 664 MachineFunction *F = BB->getParent(); 665 DebugLoc DL = MI.getDebugLoc(); 666 667 MachineRegisterInfo &RegInfo = F->getRegInfo(); 668 669 if (!isSigned) { 670 Register PromotedReg0 = RegInfo.createVirtualRegister(RC); 671 BuildMI(BB, DL, TII.get(BPF::MOV_32_64), PromotedReg0).addReg(Reg); 672 return PromotedReg0; 673 } 674 Register PromotedReg0 = RegInfo.createVirtualRegister(RC); 675 Register PromotedReg1 = RegInfo.createVirtualRegister(RC); 676 Register PromotedReg2 = RegInfo.createVirtualRegister(RC); 677 BuildMI(BB, DL, TII.get(BPF::MOV_32_64), PromotedReg0).addReg(Reg); 678 BuildMI(BB, DL, TII.get(BPF::SLL_ri), PromotedReg1) 679 .addReg(PromotedReg0).addImm(32); 680 BuildMI(BB, DL, TII.get(RShiftOp), PromotedReg2) 681 .addReg(PromotedReg1).addImm(32); 682 683 return PromotedReg2; 684 } 685 686 MachineBasicBlock * 687 BPFTargetLowering::EmitInstrWithCustomInserterMemcpy(MachineInstr &MI, 688 MachineBasicBlock *BB) 689 const { 690 MachineFunction *MF = MI.getParent()->getParent(); 691 MachineRegisterInfo &MRI = MF->getRegInfo(); 692 MachineInstrBuilder MIB(*MF, MI); 693 unsigned ScratchReg; 694 695 // This function does custom insertion during lowering BPFISD::MEMCPY which 696 // only has two register operands from memcpy semantics, the copy source 697 // address and the copy destination address. 698 // 699 // Because we will expand BPFISD::MEMCPY into load/store pairs, we will need 700 // a third scratch register to serve as the destination register of load and 701 // source register of store. 702 // 703 // The scratch register here is with the Define | Dead | EarlyClobber flags. 704 // The EarlyClobber flag has the semantic property that the operand it is 705 // attached to is clobbered before the rest of the inputs are read. Hence it 706 // must be unique among the operands to the instruction. The Define flag is 707 // needed to coerce the machine verifier that an Undef value isn't a problem 708 // as we anyway is loading memory into it. The Dead flag is needed as the 709 // value in scratch isn't supposed to be used by any other instruction. 710 ScratchReg = MRI.createVirtualRegister(&BPF::GPRRegClass); 711 MIB.addReg(ScratchReg, 712 RegState::Define | RegState::Dead | RegState::EarlyClobber); 713 714 return BB; 715 } 716 717 MachineBasicBlock * 718 BPFTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 719 MachineBasicBlock *BB) const { 720 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 721 DebugLoc DL = MI.getDebugLoc(); 722 unsigned Opc = MI.getOpcode(); 723 bool isSelectRROp = (Opc == BPF::Select || 724 Opc == BPF::Select_64_32 || 725 Opc == BPF::Select_32 || 726 Opc == BPF::Select_32_64); 727 728 bool isMemcpyOp = Opc == BPF::MEMCPY; 729 730 #ifndef NDEBUG 731 bool isSelectRIOp = (Opc == BPF::Select_Ri || 732 Opc == BPF::Select_Ri_64_32 || 733 Opc == BPF::Select_Ri_32 || 734 Opc == BPF::Select_Ri_32_64); 735 736 737 assert((isSelectRROp || isSelectRIOp || isMemcpyOp) && 738 "Unexpected instr type to insert"); 739 #endif 740 741 if (isMemcpyOp) 742 return EmitInstrWithCustomInserterMemcpy(MI, BB); 743 744 bool is32BitCmp = (Opc == BPF::Select_32 || 745 Opc == BPF::Select_32_64 || 746 Opc == BPF::Select_Ri_32 || 747 Opc == BPF::Select_Ri_32_64); 748 749 // To "insert" a SELECT instruction, we actually have to insert the diamond 750 // control-flow pattern. The incoming instruction knows the destination vreg 751 // to set, the condition code register to branch on, the true/false values to 752 // select between, and a branch opcode to use. 753 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 754 MachineFunction::iterator I = ++BB->getIterator(); 755 756 // ThisMBB: 757 // ... 758 // TrueVal = ... 759 // jmp_XX r1, r2 goto Copy1MBB 760 // fallthrough --> Copy0MBB 761 MachineBasicBlock *ThisMBB = BB; 762 MachineFunction *F = BB->getParent(); 763 MachineBasicBlock *Copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 764 MachineBasicBlock *Copy1MBB = F->CreateMachineBasicBlock(LLVM_BB); 765 766 F->insert(I, Copy0MBB); 767 F->insert(I, Copy1MBB); 768 // Update machine-CFG edges by transferring all successors of the current 769 // block to the new block which will contain the Phi node for the select. 770 Copy1MBB->splice(Copy1MBB->begin(), BB, 771 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 772 Copy1MBB->transferSuccessorsAndUpdatePHIs(BB); 773 // Next, add the true and fallthrough blocks as its successors. 774 BB->addSuccessor(Copy0MBB); 775 BB->addSuccessor(Copy1MBB); 776 777 // Insert Branch if Flag 778 int CC = MI.getOperand(3).getImm(); 779 int NewCC; 780 switch (CC) { 781 #define SET_NEWCC(X, Y) \ 782 case ISD::X: \ 783 if (is32BitCmp && HasJmp32) \ 784 NewCC = isSelectRROp ? BPF::Y##_rr_32 : BPF::Y##_ri_32; \ 785 else \ 786 NewCC = isSelectRROp ? BPF::Y##_rr : BPF::Y##_ri; \ 787 break 788 SET_NEWCC(SETGT, JSGT); 789 SET_NEWCC(SETUGT, JUGT); 790 SET_NEWCC(SETGE, JSGE); 791 SET_NEWCC(SETUGE, JUGE); 792 SET_NEWCC(SETEQ, JEQ); 793 SET_NEWCC(SETNE, JNE); 794 SET_NEWCC(SETLT, JSLT); 795 SET_NEWCC(SETULT, JULT); 796 SET_NEWCC(SETLE, JSLE); 797 SET_NEWCC(SETULE, JULE); 798 default: 799 report_fatal_error("unimplemented select CondCode " + Twine(CC)); 800 } 801 802 Register LHS = MI.getOperand(1).getReg(); 803 bool isSignedCmp = (CC == ISD::SETGT || 804 CC == ISD::SETGE || 805 CC == ISD::SETLT || 806 CC == ISD::SETLE); 807 808 // eBPF at the moment only has 64-bit comparison. Any 32-bit comparison need 809 // to be promoted, however if the 32-bit comparison operands are destination 810 // registers then they are implicitly zero-extended already, there is no 811 // need of explicit zero-extend sequence for them. 812 // 813 // We simply do extension for all situations in this method, but we will 814 // try to remove those unnecessary in BPFMIPeephole pass. 815 if (is32BitCmp && !HasJmp32) 816 LHS = EmitSubregExt(MI, BB, LHS, isSignedCmp); 817 818 if (isSelectRROp) { 819 Register RHS = MI.getOperand(2).getReg(); 820 821 if (is32BitCmp && !HasJmp32) 822 RHS = EmitSubregExt(MI, BB, RHS, isSignedCmp); 823 824 BuildMI(BB, DL, TII.get(NewCC)).addReg(LHS).addReg(RHS).addMBB(Copy1MBB); 825 } else { 826 int64_t imm32 = MI.getOperand(2).getImm(); 827 // Check before we build J*_ri instruction. 828 assert (isInt<32>(imm32)); 829 BuildMI(BB, DL, TII.get(NewCC)) 830 .addReg(LHS).addImm(imm32).addMBB(Copy1MBB); 831 } 832 833 // Copy0MBB: 834 // %FalseValue = ... 835 // # fallthrough to Copy1MBB 836 BB = Copy0MBB; 837 838 // Update machine-CFG edges 839 BB->addSuccessor(Copy1MBB); 840 841 // Copy1MBB: 842 // %Result = phi [ %FalseValue, Copy0MBB ], [ %TrueValue, ThisMBB ] 843 // ... 844 BB = Copy1MBB; 845 BuildMI(*BB, BB->begin(), DL, TII.get(BPF::PHI), MI.getOperand(0).getReg()) 846 .addReg(MI.getOperand(5).getReg()) 847 .addMBB(Copy0MBB) 848 .addReg(MI.getOperand(4).getReg()) 849 .addMBB(ThisMBB); 850 851 MI.eraseFromParent(); // The pseudo instruction is gone now. 852 return BB; 853 } 854 855 EVT BPFTargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &, 856 EVT VT) const { 857 return getHasAlu32() ? MVT::i32 : MVT::i64; 858 } 859 860 MVT BPFTargetLowering::getScalarShiftAmountTy(const DataLayout &DL, 861 EVT VT) const { 862 return (getHasAlu32() && VT == MVT::i32) ? MVT::i32 : MVT::i64; 863 } 864 865 bool BPFTargetLowering::isLegalAddressingMode(const DataLayout &DL, 866 const AddrMode &AM, Type *Ty, 867 unsigned AS, 868 Instruction *I) const { 869 // No global is ever allowed as a base. 870 if (AM.BaseGV) 871 return false; 872 873 switch (AM.Scale) { 874 case 0: // "r+i" or just "i", depending on HasBaseReg. 875 break; 876 case 1: 877 if (!AM.HasBaseReg) // allow "r+i". 878 break; 879 return false; // disallow "r+r" or "r+r+i". 880 default: 881 return false; 882 } 883 884 return true; 885 } 886