1 //===-- AVRISelLowering.cpp - AVR 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 AVR uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "AVRISelLowering.h" 15 16 #include "llvm/ADT/StringSwitch.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/CodeGen/CallingConvLower.h" 19 #include "llvm/CodeGen/MachineFrameInfo.h" 20 #include "llvm/CodeGen/MachineInstrBuilder.h" 21 #include "llvm/CodeGen/MachineRegisterInfo.h" 22 #include "llvm/CodeGen/SelectionDAG.h" 23 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 24 #include "llvm/IR/Function.h" 25 #include "llvm/Support/ErrorHandling.h" 26 27 #include "AVR.h" 28 #include "AVRMachineFunctionInfo.h" 29 #include "AVRSubtarget.h" 30 #include "AVRTargetMachine.h" 31 #include "MCTargetDesc/AVRMCTargetDesc.h" 32 33 namespace llvm { 34 35 AVRTargetLowering::AVRTargetLowering(const AVRTargetMachine &TM, 36 const AVRSubtarget &STI) 37 : TargetLowering(TM), Subtarget(STI) { 38 // Set up the register classes. 39 addRegisterClass(MVT::i8, &AVR::GPR8RegClass); 40 addRegisterClass(MVT::i16, &AVR::DREGSRegClass); 41 42 // Compute derived properties from the register classes. 43 computeRegisterProperties(Subtarget.getRegisterInfo()); 44 45 setBooleanContents(ZeroOrOneBooleanContent); 46 setBooleanVectorContents(ZeroOrOneBooleanContent); 47 setSchedulingPreference(Sched::RegPressure); 48 setStackPointerRegisterToSaveRestore(AVR::SP); 49 setSupportsUnalignedAtomics(true); 50 51 setOperationAction(ISD::GlobalAddress, MVT::i16, Custom); 52 setOperationAction(ISD::BlockAddress, MVT::i16, Custom); 53 54 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 55 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 56 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i8, Expand); 57 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i16, Expand); 58 59 for (MVT VT : MVT::integer_valuetypes()) { 60 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) { 61 setLoadExtAction(N, VT, MVT::i1, Promote); 62 setLoadExtAction(N, VT, MVT::i8, Expand); 63 } 64 } 65 66 setTruncStoreAction(MVT::i16, MVT::i8, Expand); 67 68 for (MVT VT : MVT::integer_valuetypes()) { 69 setOperationAction(ISD::ADDC, VT, Legal); 70 setOperationAction(ISD::SUBC, VT, Legal); 71 setOperationAction(ISD::ADDE, VT, Legal); 72 setOperationAction(ISD::SUBE, VT, Legal); 73 } 74 75 // sub (x, imm) gets canonicalized to add (x, -imm), so for illegal types 76 // revert into a sub since we don't have an add with immediate instruction. 77 setOperationAction(ISD::ADD, MVT::i32, Custom); 78 setOperationAction(ISD::ADD, MVT::i64, Custom); 79 80 // our shift instructions are only able to shift 1 bit at a time, so handle 81 // this in a custom way. 82 setOperationAction(ISD::SRA, MVT::i8, Custom); 83 setOperationAction(ISD::SHL, MVT::i8, Custom); 84 setOperationAction(ISD::SRL, MVT::i8, Custom); 85 setOperationAction(ISD::SRA, MVT::i16, Custom); 86 setOperationAction(ISD::SHL, MVT::i16, Custom); 87 setOperationAction(ISD::SRL, MVT::i16, Custom); 88 setOperationAction(ISD::SHL_PARTS, MVT::i16, Expand); 89 setOperationAction(ISD::SRA_PARTS, MVT::i16, Expand); 90 setOperationAction(ISD::SRL_PARTS, MVT::i16, Expand); 91 92 setOperationAction(ISD::ROTL, MVT::i8, Custom); 93 setOperationAction(ISD::ROTL, MVT::i16, Expand); 94 setOperationAction(ISD::ROTR, MVT::i8, Custom); 95 setOperationAction(ISD::ROTR, MVT::i16, Expand); 96 97 setOperationAction(ISD::BR_CC, MVT::i8, Custom); 98 setOperationAction(ISD::BR_CC, MVT::i16, Custom); 99 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 100 setOperationAction(ISD::BR_CC, MVT::i64, Custom); 101 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 102 103 setOperationAction(ISD::SELECT_CC, MVT::i8, Custom); 104 setOperationAction(ISD::SELECT_CC, MVT::i16, Custom); 105 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 106 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 107 setOperationAction(ISD::SETCC, MVT::i8, Custom); 108 setOperationAction(ISD::SETCC, MVT::i16, Custom); 109 setOperationAction(ISD::SETCC, MVT::i32, Custom); 110 setOperationAction(ISD::SETCC, MVT::i64, Custom); 111 setOperationAction(ISD::SELECT, MVT::i8, Expand); 112 setOperationAction(ISD::SELECT, MVT::i16, Expand); 113 114 setOperationAction(ISD::BSWAP, MVT::i16, Expand); 115 116 // Add support for postincrement and predecrement load/stores. 117 setIndexedLoadAction(ISD::POST_INC, MVT::i8, Legal); 118 setIndexedLoadAction(ISD::POST_INC, MVT::i16, Legal); 119 setIndexedLoadAction(ISD::PRE_DEC, MVT::i8, Legal); 120 setIndexedLoadAction(ISD::PRE_DEC, MVT::i16, Legal); 121 setIndexedStoreAction(ISD::POST_INC, MVT::i8, Legal); 122 setIndexedStoreAction(ISD::POST_INC, MVT::i16, Legal); 123 setIndexedStoreAction(ISD::PRE_DEC, MVT::i8, Legal); 124 setIndexedStoreAction(ISD::PRE_DEC, MVT::i16, Legal); 125 126 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 127 128 setOperationAction(ISD::VASTART, MVT::Other, Custom); 129 setOperationAction(ISD::VAEND, MVT::Other, Expand); 130 setOperationAction(ISD::VAARG, MVT::Other, Expand); 131 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 132 133 // Atomic operations which must be lowered to rtlib calls 134 for (MVT VT : MVT::integer_valuetypes()) { 135 setOperationAction(ISD::ATOMIC_SWAP, VT, Expand); 136 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Expand); 137 setOperationAction(ISD::ATOMIC_LOAD_NAND, VT, Expand); 138 setOperationAction(ISD::ATOMIC_LOAD_MAX, VT, Expand); 139 setOperationAction(ISD::ATOMIC_LOAD_MIN, VT, Expand); 140 setOperationAction(ISD::ATOMIC_LOAD_UMAX, VT, Expand); 141 setOperationAction(ISD::ATOMIC_LOAD_UMIN, VT, Expand); 142 } 143 144 // Division/remainder 145 setOperationAction(ISD::UDIV, MVT::i8, Expand); 146 setOperationAction(ISD::UDIV, MVT::i16, Expand); 147 setOperationAction(ISD::UREM, MVT::i8, Expand); 148 setOperationAction(ISD::UREM, MVT::i16, Expand); 149 setOperationAction(ISD::SDIV, MVT::i8, Expand); 150 setOperationAction(ISD::SDIV, MVT::i16, Expand); 151 setOperationAction(ISD::SREM, MVT::i8, Expand); 152 setOperationAction(ISD::SREM, MVT::i16, Expand); 153 154 // Make division and modulus custom 155 setOperationAction(ISD::UDIVREM, MVT::i8, Custom); 156 setOperationAction(ISD::UDIVREM, MVT::i16, Custom); 157 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 158 setOperationAction(ISD::SDIVREM, MVT::i8, Custom); 159 setOperationAction(ISD::SDIVREM, MVT::i16, Custom); 160 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 161 162 // Do not use MUL. The AVR instructions are closer to SMUL_LOHI &co. 163 setOperationAction(ISD::MUL, MVT::i8, Expand); 164 setOperationAction(ISD::MUL, MVT::i16, Expand); 165 166 // Expand 16 bit multiplications. 167 setOperationAction(ISD::SMUL_LOHI, MVT::i16, Expand); 168 setOperationAction(ISD::UMUL_LOHI, MVT::i16, Expand); 169 170 // Expand multiplications to libcalls when there is 171 // no hardware MUL. 172 if (!Subtarget.supportsMultiplication()) { 173 setOperationAction(ISD::SMUL_LOHI, MVT::i8, Expand); 174 setOperationAction(ISD::UMUL_LOHI, MVT::i8, Expand); 175 } 176 177 for (MVT VT : MVT::integer_valuetypes()) { 178 setOperationAction(ISD::MULHS, VT, Expand); 179 setOperationAction(ISD::MULHU, VT, Expand); 180 } 181 182 for (MVT VT : MVT::integer_valuetypes()) { 183 setOperationAction(ISD::CTPOP, VT, Expand); 184 setOperationAction(ISD::CTLZ, VT, Expand); 185 setOperationAction(ISD::CTTZ, VT, Expand); 186 } 187 188 for (MVT VT : MVT::integer_valuetypes()) { 189 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 190 // TODO: The generated code is pretty poor. Investigate using the 191 // same "shift and subtract with carry" trick that we do for 192 // extending 8-bit to 16-bit. This may require infrastructure 193 // improvements in how we treat 16-bit "registers" to be feasible. 194 } 195 196 // Division rtlib functions (not supported), use divmod functions instead 197 setLibcallName(RTLIB::SDIV_I8, nullptr); 198 setLibcallName(RTLIB::SDIV_I16, nullptr); 199 setLibcallName(RTLIB::SDIV_I32, nullptr); 200 setLibcallName(RTLIB::UDIV_I8, nullptr); 201 setLibcallName(RTLIB::UDIV_I16, nullptr); 202 setLibcallName(RTLIB::UDIV_I32, nullptr); 203 204 // Modulus rtlib functions (not supported), use divmod functions instead 205 setLibcallName(RTLIB::SREM_I8, nullptr); 206 setLibcallName(RTLIB::SREM_I16, nullptr); 207 setLibcallName(RTLIB::SREM_I32, nullptr); 208 setLibcallName(RTLIB::UREM_I8, nullptr); 209 setLibcallName(RTLIB::UREM_I16, nullptr); 210 setLibcallName(RTLIB::UREM_I32, nullptr); 211 212 // Division and modulus rtlib functions 213 setLibcallName(RTLIB::SDIVREM_I8, "__divmodqi4"); 214 setLibcallName(RTLIB::SDIVREM_I16, "__divmodhi4"); 215 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 216 setLibcallName(RTLIB::UDIVREM_I8, "__udivmodqi4"); 217 setLibcallName(RTLIB::UDIVREM_I16, "__udivmodhi4"); 218 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 219 220 // Several of the runtime library functions use a special calling conv 221 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::AVR_BUILTIN); 222 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::AVR_BUILTIN); 223 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::AVR_BUILTIN); 224 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::AVR_BUILTIN); 225 226 // Trigonometric rtlib functions 227 setLibcallName(RTLIB::SIN_F32, "sin"); 228 setLibcallName(RTLIB::COS_F32, "cos"); 229 230 setMinFunctionAlignment(Align(2)); 231 setMinimumJumpTableEntries(UINT_MAX); 232 } 233 234 const char *AVRTargetLowering::getTargetNodeName(unsigned Opcode) const { 235 #define NODE(name) \ 236 case AVRISD::name: \ 237 return #name 238 239 switch (Opcode) { 240 default: 241 return nullptr; 242 NODE(RET_FLAG); 243 NODE(RETI_FLAG); 244 NODE(CALL); 245 NODE(WRAPPER); 246 NODE(LSL); 247 NODE(LSR); 248 NODE(ROL); 249 NODE(ROR); 250 NODE(ASR); 251 NODE(LSLLOOP); 252 NODE(LSRLOOP); 253 NODE(ROLLOOP); 254 NODE(RORLOOP); 255 NODE(ASRLOOP); 256 NODE(BRCOND); 257 NODE(CMP); 258 NODE(CMPC); 259 NODE(TST); 260 NODE(SELECT_CC); 261 #undef NODE 262 } 263 } 264 265 EVT AVRTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 266 EVT VT) const { 267 assert(!VT.isVector() && "No AVR SetCC type for vectors!"); 268 return MVT::i8; 269 } 270 271 SDValue AVRTargetLowering::LowerShifts(SDValue Op, SelectionDAG &DAG) const { 272 //:TODO: this function has to be completely rewritten to produce optimal 273 // code, for now it's producing very long but correct code. 274 unsigned Opc8; 275 const SDNode *N = Op.getNode(); 276 EVT VT = Op.getValueType(); 277 SDLoc dl(N); 278 assert(isPowerOf2_32(VT.getSizeInBits()) && 279 "Expected power-of-2 shift amount"); 280 281 // Expand non-constant shifts to loops. 282 if (!isa<ConstantSDNode>(N->getOperand(1))) { 283 switch (Op.getOpcode()) { 284 default: 285 llvm_unreachable("Invalid shift opcode!"); 286 case ISD::SHL: 287 return DAG.getNode(AVRISD::LSLLOOP, dl, VT, N->getOperand(0), 288 N->getOperand(1)); 289 case ISD::SRL: 290 return DAG.getNode(AVRISD::LSRLOOP, dl, VT, N->getOperand(0), 291 N->getOperand(1)); 292 case ISD::ROTL: { 293 SDValue Amt = N->getOperand(1); 294 EVT AmtVT = Amt.getValueType(); 295 Amt = DAG.getNode(ISD::AND, dl, AmtVT, Amt, 296 DAG.getConstant(VT.getSizeInBits() - 1, dl, AmtVT)); 297 return DAG.getNode(AVRISD::ROLLOOP, dl, VT, N->getOperand(0), Amt); 298 } 299 case ISD::ROTR: { 300 SDValue Amt = N->getOperand(1); 301 EVT AmtVT = Amt.getValueType(); 302 Amt = DAG.getNode(ISD::AND, dl, AmtVT, Amt, 303 DAG.getConstant(VT.getSizeInBits() - 1, dl, AmtVT)); 304 return DAG.getNode(AVRISD::RORLOOP, dl, VT, N->getOperand(0), Amt); 305 } 306 case ISD::SRA: 307 return DAG.getNode(AVRISD::ASRLOOP, dl, VT, N->getOperand(0), 308 N->getOperand(1)); 309 } 310 } 311 312 uint64_t ShiftAmount = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 313 SDValue Victim = N->getOperand(0); 314 315 switch (Op.getOpcode()) { 316 case ISD::SRA: 317 Opc8 = AVRISD::ASR; 318 break; 319 case ISD::ROTL: 320 Opc8 = AVRISD::ROL; 321 ShiftAmount = ShiftAmount % VT.getSizeInBits(); 322 break; 323 case ISD::ROTR: 324 Opc8 = AVRISD::ROR; 325 ShiftAmount = ShiftAmount % VT.getSizeInBits(); 326 break; 327 case ISD::SRL: 328 Opc8 = AVRISD::LSR; 329 break; 330 case ISD::SHL: 331 Opc8 = AVRISD::LSL; 332 break; 333 default: 334 llvm_unreachable("Invalid shift opcode"); 335 } 336 337 while (ShiftAmount--) { 338 Victim = DAG.getNode(Opc8, dl, VT, Victim); 339 } 340 341 return Victim; 342 } 343 344 SDValue AVRTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 345 unsigned Opcode = Op->getOpcode(); 346 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 347 "Invalid opcode for Div/Rem lowering"); 348 bool IsSigned = (Opcode == ISD::SDIVREM); 349 EVT VT = Op->getValueType(0); 350 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 351 352 RTLIB::Libcall LC; 353 switch (VT.getSimpleVT().SimpleTy) { 354 default: 355 llvm_unreachable("Unexpected request for libcall!"); 356 case MVT::i8: 357 LC = IsSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; 358 break; 359 case MVT::i16: 360 LC = IsSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; 361 break; 362 case MVT::i32: 363 LC = IsSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; 364 break; 365 } 366 367 SDValue InChain = DAG.getEntryNode(); 368 369 TargetLowering::ArgListTy Args; 370 TargetLowering::ArgListEntry Entry; 371 for (SDValue const &Value : Op->op_values()) { 372 Entry.Node = Value; 373 Entry.Ty = Value.getValueType().getTypeForEVT(*DAG.getContext()); 374 Entry.IsSExt = IsSigned; 375 Entry.IsZExt = !IsSigned; 376 Args.push_back(Entry); 377 } 378 379 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 380 getPointerTy(DAG.getDataLayout())); 381 382 Type *RetTy = (Type *)StructType::get(Ty, Ty); 383 384 SDLoc dl(Op); 385 TargetLowering::CallLoweringInfo CLI(DAG); 386 CLI.setDebugLoc(dl) 387 .setChain(InChain) 388 .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 389 .setInRegister() 390 .setSExtResult(IsSigned) 391 .setZExtResult(!IsSigned); 392 393 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 394 return CallInfo.first; 395 } 396 397 SDValue AVRTargetLowering::LowerGlobalAddress(SDValue Op, 398 SelectionDAG &DAG) const { 399 auto DL = DAG.getDataLayout(); 400 401 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 402 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset(); 403 404 // Create the TargetGlobalAddress node, folding in the constant offset. 405 SDValue Result = 406 DAG.getTargetGlobalAddress(GV, SDLoc(Op), getPointerTy(DL), Offset); 407 return DAG.getNode(AVRISD::WRAPPER, SDLoc(Op), getPointerTy(DL), Result); 408 } 409 410 SDValue AVRTargetLowering::LowerBlockAddress(SDValue Op, 411 SelectionDAG &DAG) const { 412 auto DL = DAG.getDataLayout(); 413 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 414 415 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(DL)); 416 417 return DAG.getNode(AVRISD::WRAPPER, SDLoc(Op), getPointerTy(DL), Result); 418 } 419 420 /// IntCCToAVRCC - Convert a DAG integer condition code to an AVR CC. 421 static AVRCC::CondCodes intCCToAVRCC(ISD::CondCode CC) { 422 switch (CC) { 423 default: 424 llvm_unreachable("Unknown condition code!"); 425 case ISD::SETEQ: 426 return AVRCC::COND_EQ; 427 case ISD::SETNE: 428 return AVRCC::COND_NE; 429 case ISD::SETGE: 430 return AVRCC::COND_GE; 431 case ISD::SETLT: 432 return AVRCC::COND_LT; 433 case ISD::SETUGE: 434 return AVRCC::COND_SH; 435 case ISD::SETULT: 436 return AVRCC::COND_LO; 437 } 438 } 439 440 /// Returns appropriate AVR CMP/CMPC nodes and corresponding condition code for 441 /// the given operands. 442 SDValue AVRTargetLowering::getAVRCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 443 SDValue &AVRcc, SelectionDAG &DAG, 444 SDLoc DL) const { 445 SDValue Cmp; 446 EVT VT = LHS.getValueType(); 447 bool UseTest = false; 448 449 switch (CC) { 450 default: 451 break; 452 case ISD::SETLE: { 453 // Swap operands and reverse the branching condition. 454 std::swap(LHS, RHS); 455 CC = ISD::SETGE; 456 break; 457 } 458 case ISD::SETGT: { 459 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 460 switch (C->getSExtValue()) { 461 case -1: { 462 // When doing lhs > -1 use a tst instruction on the top part of lhs 463 // and use brpl instead of using a chain of cp/cpc. 464 UseTest = true; 465 AVRcc = DAG.getConstant(AVRCC::COND_PL, DL, MVT::i8); 466 break; 467 } 468 case 0: { 469 // Turn lhs > 0 into 0 < lhs since 0 can be materialized with 470 // __zero_reg__ in lhs. 471 RHS = LHS; 472 LHS = DAG.getConstant(0, DL, VT); 473 CC = ISD::SETLT; 474 break; 475 } 476 default: { 477 // Turn lhs < rhs with lhs constant into rhs >= lhs+1, this allows 478 // us to fold the constant into the cmp instruction. 479 RHS = DAG.getConstant(C->getSExtValue() + 1, DL, VT); 480 CC = ISD::SETGE; 481 break; 482 } 483 } 484 break; 485 } 486 // Swap operands and reverse the branching condition. 487 std::swap(LHS, RHS); 488 CC = ISD::SETLT; 489 break; 490 } 491 case ISD::SETLT: { 492 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 493 switch (C->getSExtValue()) { 494 case 1: { 495 // Turn lhs < 1 into 0 >= lhs since 0 can be materialized with 496 // __zero_reg__ in lhs. 497 RHS = LHS; 498 LHS = DAG.getConstant(0, DL, VT); 499 CC = ISD::SETGE; 500 break; 501 } 502 case 0: { 503 // When doing lhs < 0 use a tst instruction on the top part of lhs 504 // and use brmi instead of using a chain of cp/cpc. 505 UseTest = true; 506 AVRcc = DAG.getConstant(AVRCC::COND_MI, DL, MVT::i8); 507 break; 508 } 509 } 510 } 511 break; 512 } 513 case ISD::SETULE: { 514 // Swap operands and reverse the branching condition. 515 std::swap(LHS, RHS); 516 CC = ISD::SETUGE; 517 break; 518 } 519 case ISD::SETUGT: { 520 // Turn lhs < rhs with lhs constant into rhs >= lhs+1, this allows us to 521 // fold the constant into the cmp instruction. 522 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 523 RHS = DAG.getConstant(C->getSExtValue() + 1, DL, VT); 524 CC = ISD::SETUGE; 525 break; 526 } 527 // Swap operands and reverse the branching condition. 528 std::swap(LHS, RHS); 529 CC = ISD::SETULT; 530 break; 531 } 532 } 533 534 // Expand 32 and 64 bit comparisons with custom CMP and CMPC nodes instead of 535 // using the default and/or/xor expansion code which is much longer. 536 if (VT == MVT::i32) { 537 SDValue LHSlo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS, 538 DAG.getIntPtrConstant(0, DL)); 539 SDValue LHShi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS, 540 DAG.getIntPtrConstant(1, DL)); 541 SDValue RHSlo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS, 542 DAG.getIntPtrConstant(0, DL)); 543 SDValue RHShi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS, 544 DAG.getIntPtrConstant(1, DL)); 545 546 if (UseTest) { 547 // When using tst we only care about the highest part. 548 SDValue Top = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, LHShi, 549 DAG.getIntPtrConstant(1, DL)); 550 Cmp = DAG.getNode(AVRISD::TST, DL, MVT::Glue, Top); 551 } else { 552 Cmp = DAG.getNode(AVRISD::CMP, DL, MVT::Glue, LHSlo, RHSlo); 553 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHShi, RHShi, Cmp); 554 } 555 } else if (VT == MVT::i64) { 556 SDValue LHS_0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, LHS, 557 DAG.getIntPtrConstant(0, DL)); 558 SDValue LHS_1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, LHS, 559 DAG.getIntPtrConstant(1, DL)); 560 561 SDValue LHS0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS_0, 562 DAG.getIntPtrConstant(0, DL)); 563 SDValue LHS1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS_0, 564 DAG.getIntPtrConstant(1, DL)); 565 SDValue LHS2 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS_1, 566 DAG.getIntPtrConstant(0, DL)); 567 SDValue LHS3 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS_1, 568 DAG.getIntPtrConstant(1, DL)); 569 570 SDValue RHS_0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, RHS, 571 DAG.getIntPtrConstant(0, DL)); 572 SDValue RHS_1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, RHS, 573 DAG.getIntPtrConstant(1, DL)); 574 575 SDValue RHS0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS_0, 576 DAG.getIntPtrConstant(0, DL)); 577 SDValue RHS1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS_0, 578 DAG.getIntPtrConstant(1, DL)); 579 SDValue RHS2 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS_1, 580 DAG.getIntPtrConstant(0, DL)); 581 SDValue RHS3 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS_1, 582 DAG.getIntPtrConstant(1, DL)); 583 584 if (UseTest) { 585 // When using tst we only care about the highest part. 586 SDValue Top = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, LHS3, 587 DAG.getIntPtrConstant(1, DL)); 588 Cmp = DAG.getNode(AVRISD::TST, DL, MVT::Glue, Top); 589 } else { 590 Cmp = DAG.getNode(AVRISD::CMP, DL, MVT::Glue, LHS0, RHS0); 591 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHS1, RHS1, Cmp); 592 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHS2, RHS2, Cmp); 593 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHS3, RHS3, Cmp); 594 } 595 } else if (VT == MVT::i8 || VT == MVT::i16) { 596 if (UseTest) { 597 // When using tst we only care about the highest part. 598 Cmp = DAG.getNode(AVRISD::TST, DL, MVT::Glue, 599 (VT == MVT::i8) 600 ? LHS 601 : DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, 602 LHS, DAG.getIntPtrConstant(1, DL))); 603 } else { 604 Cmp = DAG.getNode(AVRISD::CMP, DL, MVT::Glue, LHS, RHS); 605 } 606 } else { 607 llvm_unreachable("Invalid comparison size"); 608 } 609 610 // When using a test instruction AVRcc is already set. 611 if (!UseTest) { 612 AVRcc = DAG.getConstant(intCCToAVRCC(CC), DL, MVT::i8); 613 } 614 615 return Cmp; 616 } 617 618 SDValue AVRTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 619 SDValue Chain = Op.getOperand(0); 620 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 621 SDValue LHS = Op.getOperand(2); 622 SDValue RHS = Op.getOperand(3); 623 SDValue Dest = Op.getOperand(4); 624 SDLoc dl(Op); 625 626 SDValue TargetCC; 627 SDValue Cmp = getAVRCmp(LHS, RHS, CC, TargetCC, DAG, dl); 628 629 return DAG.getNode(AVRISD::BRCOND, dl, MVT::Other, Chain, Dest, TargetCC, 630 Cmp); 631 } 632 633 SDValue AVRTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 634 SDValue LHS = Op.getOperand(0); 635 SDValue RHS = Op.getOperand(1); 636 SDValue TrueV = Op.getOperand(2); 637 SDValue FalseV = Op.getOperand(3); 638 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 639 SDLoc dl(Op); 640 641 SDValue TargetCC; 642 SDValue Cmp = getAVRCmp(LHS, RHS, CC, TargetCC, DAG, dl); 643 644 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue); 645 SDValue Ops[] = {TrueV, FalseV, TargetCC, Cmp}; 646 647 return DAG.getNode(AVRISD::SELECT_CC, dl, VTs, Ops); 648 } 649 650 SDValue AVRTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 651 SDValue LHS = Op.getOperand(0); 652 SDValue RHS = Op.getOperand(1); 653 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 654 SDLoc DL(Op); 655 656 SDValue TargetCC; 657 SDValue Cmp = getAVRCmp(LHS, RHS, CC, TargetCC, DAG, DL); 658 659 SDValue TrueV = DAG.getConstant(1, DL, Op.getValueType()); 660 SDValue FalseV = DAG.getConstant(0, DL, Op.getValueType()); 661 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue); 662 SDValue Ops[] = {TrueV, FalseV, TargetCC, Cmp}; 663 664 return DAG.getNode(AVRISD::SELECT_CC, DL, VTs, Ops); 665 } 666 667 SDValue AVRTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 668 const MachineFunction &MF = DAG.getMachineFunction(); 669 const AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>(); 670 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 671 auto DL = DAG.getDataLayout(); 672 SDLoc dl(Op); 673 674 // Vastart just stores the address of the VarArgsFrameIndex slot into the 675 // memory location argument. 676 SDValue FI = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(), getPointerTy(DL)); 677 678 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1), 679 MachinePointerInfo(SV)); 680 } 681 682 SDValue AVRTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 683 switch (Op.getOpcode()) { 684 default: 685 llvm_unreachable("Don't know how to custom lower this!"); 686 case ISD::SHL: 687 case ISD::SRA: 688 case ISD::SRL: 689 case ISD::ROTL: 690 case ISD::ROTR: 691 return LowerShifts(Op, DAG); 692 case ISD::GlobalAddress: 693 return LowerGlobalAddress(Op, DAG); 694 case ISD::BlockAddress: 695 return LowerBlockAddress(Op, DAG); 696 case ISD::BR_CC: 697 return LowerBR_CC(Op, DAG); 698 case ISD::SELECT_CC: 699 return LowerSELECT_CC(Op, DAG); 700 case ISD::SETCC: 701 return LowerSETCC(Op, DAG); 702 case ISD::VASTART: 703 return LowerVASTART(Op, DAG); 704 case ISD::SDIVREM: 705 case ISD::UDIVREM: 706 return LowerDivRem(Op, DAG); 707 } 708 709 return SDValue(); 710 } 711 712 /// Replace a node with an illegal result type 713 /// with a new node built out of custom code. 714 void AVRTargetLowering::ReplaceNodeResults(SDNode *N, 715 SmallVectorImpl<SDValue> &Results, 716 SelectionDAG &DAG) const { 717 SDLoc DL(N); 718 719 switch (N->getOpcode()) { 720 case ISD::ADD: { 721 // Convert add (x, imm) into sub (x, -imm). 722 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) { 723 SDValue Sub = DAG.getNode( 724 ISD::SUB, DL, N->getValueType(0), N->getOperand(0), 725 DAG.getConstant(-C->getAPIntValue(), DL, C->getValueType(0))); 726 Results.push_back(Sub); 727 } 728 break; 729 } 730 default: { 731 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 732 733 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I) 734 Results.push_back(Res.getValue(I)); 735 736 break; 737 } 738 } 739 } 740 741 /// Return true if the addressing mode represented 742 /// by AM is legal for this target, for a load/store of the specified type. 743 bool AVRTargetLowering::isLegalAddressingMode(const DataLayout &DL, 744 const AddrMode &AM, Type *Ty, 745 unsigned AS, Instruction *I) const { 746 int64_t Offs = AM.BaseOffs; 747 748 // Allow absolute addresses. 749 if (AM.BaseGV && !AM.HasBaseReg && AM.Scale == 0 && Offs == 0) { 750 return true; 751 } 752 753 // Flash memory instructions only allow zero offsets. 754 if (isa<PointerType>(Ty) && AS == AVR::ProgramMemory) { 755 return false; 756 } 757 758 // Allow reg+<6bit> offset. 759 if (Offs < 0) 760 Offs = -Offs; 761 if (AM.BaseGV == 0 && AM.HasBaseReg && AM.Scale == 0 && isUInt<6>(Offs)) { 762 return true; 763 } 764 765 return false; 766 } 767 768 /// Returns true by value, base pointer and 769 /// offset pointer and addressing mode by reference if the node's address 770 /// can be legally represented as pre-indexed load / store address. 771 bool AVRTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 772 SDValue &Offset, 773 ISD::MemIndexedMode &AM, 774 SelectionDAG &DAG) const { 775 EVT VT; 776 const SDNode *Op; 777 SDLoc DL(N); 778 779 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 780 VT = LD->getMemoryVT(); 781 Op = LD->getBasePtr().getNode(); 782 if (LD->getExtensionType() != ISD::NON_EXTLOAD) 783 return false; 784 if (AVR::isProgramMemoryAccess(LD)) { 785 return false; 786 } 787 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 788 VT = ST->getMemoryVT(); 789 Op = ST->getBasePtr().getNode(); 790 if (AVR::isProgramMemoryAccess(ST)) { 791 return false; 792 } 793 } else { 794 return false; 795 } 796 797 if (VT != MVT::i8 && VT != MVT::i16) { 798 return false; 799 } 800 801 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) { 802 return false; 803 } 804 805 if (const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) { 806 int RHSC = RHS->getSExtValue(); 807 if (Op->getOpcode() == ISD::SUB) 808 RHSC = -RHSC; 809 810 if ((VT == MVT::i16 && RHSC != -2) || (VT == MVT::i8 && RHSC != -1)) { 811 return false; 812 } 813 814 Base = Op->getOperand(0); 815 Offset = DAG.getConstant(RHSC, DL, MVT::i8); 816 AM = ISD::PRE_DEC; 817 818 return true; 819 } 820 821 return false; 822 } 823 824 /// Returns true by value, base pointer and 825 /// offset pointer and addressing mode by reference if this node can be 826 /// combined with a load / store to form a post-indexed load / store. 827 bool AVRTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 828 SDValue &Base, 829 SDValue &Offset, 830 ISD::MemIndexedMode &AM, 831 SelectionDAG &DAG) const { 832 EVT VT; 833 SDLoc DL(N); 834 835 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 836 VT = LD->getMemoryVT(); 837 if (LD->getExtensionType() != ISD::NON_EXTLOAD) 838 return false; 839 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 840 VT = ST->getMemoryVT(); 841 if (AVR::isProgramMemoryAccess(ST)) { 842 return false; 843 } 844 } else { 845 return false; 846 } 847 848 if (VT != MVT::i8 && VT != MVT::i16) { 849 return false; 850 } 851 852 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) { 853 return false; 854 } 855 856 if (const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) { 857 int RHSC = RHS->getSExtValue(); 858 if (Op->getOpcode() == ISD::SUB) 859 RHSC = -RHSC; 860 if ((VT == MVT::i16 && RHSC != 2) || (VT == MVT::i8 && RHSC != 1)) { 861 return false; 862 } 863 864 Base = Op->getOperand(0); 865 Offset = DAG.getConstant(RHSC, DL, MVT::i8); 866 AM = ISD::POST_INC; 867 868 return true; 869 } 870 871 return false; 872 } 873 874 bool AVRTargetLowering::isOffsetFoldingLegal( 875 const GlobalAddressSDNode *GA) const { 876 return true; 877 } 878 879 //===----------------------------------------------------------------------===// 880 // Formal Arguments Calling Convention Implementation 881 //===----------------------------------------------------------------------===// 882 883 #include "AVRGenCallingConv.inc" 884 885 /// Registers for calling conventions, ordered in reverse as required by ABI. 886 /// Both arrays must be of the same length. 887 static const MCPhysReg RegList8[] = { 888 AVR::R25, AVR::R24, AVR::R23, AVR::R22, AVR::R21, AVR::R20, 889 AVR::R19, AVR::R18, AVR::R17, AVR::R16, AVR::R15, AVR::R14, 890 AVR::R13, AVR::R12, AVR::R11, AVR::R10, AVR::R9, AVR::R8}; 891 static const MCPhysReg RegList16[] = { 892 AVR::R26R25, AVR::R25R24, AVR::R24R23, AVR::R23R22, 893 AVR::R22R21, AVR::R21R20, AVR::R20R19, AVR::R19R18, 894 AVR::R18R17, AVR::R17R16, AVR::R16R15, AVR::R15R14, 895 AVR::R14R13, AVR::R13R12, AVR::R12R11, AVR::R11R10, 896 AVR::R10R9, AVR::R9R8}; 897 898 static_assert(array_lengthof(RegList8) == array_lengthof(RegList16), 899 "8-bit and 16-bit register arrays must be of equal length"); 900 901 /// Analyze incoming and outgoing function arguments. We need custom C++ code 902 /// to handle special constraints in the ABI. 903 /// In addition, all pieces of a certain argument have to be passed either 904 /// using registers or the stack but never mixing both. 905 template <typename ArgT> 906 static void 907 analyzeArguments(TargetLowering::CallLoweringInfo *CLI, const Function *F, 908 const DataLayout *TD, const SmallVectorImpl<ArgT> &Args, 909 SmallVectorImpl<CCValAssign> &ArgLocs, CCState &CCInfo) { 910 unsigned NumArgs = Args.size(); 911 // This is the index of the last used register, in RegList*. 912 // -1 means R26 (R26 is never actually used in CC). 913 int RegLastIdx = -1; 914 // Once a value is passed to the stack it will always be used 915 bool UseStack = false; 916 for (unsigned i = 0; i != NumArgs;) { 917 MVT VT = Args[i].VT; 918 // We have to count the number of bytes for each function argument, that is 919 // those Args with the same OrigArgIndex. This is important in case the 920 // function takes an aggregate type. 921 // Current argument will be between [i..j). 922 unsigned ArgIndex = Args[i].OrigArgIndex; 923 unsigned TotalBytes = VT.getStoreSize(); 924 unsigned j = i + 1; 925 for (; j != NumArgs; ++j) { 926 if (Args[j].OrigArgIndex != ArgIndex) 927 break; 928 TotalBytes += Args[j].VT.getStoreSize(); 929 } 930 // Round up to even number of bytes. 931 TotalBytes = alignTo(TotalBytes, 2); 932 // Skip zero sized arguments 933 if (TotalBytes == 0) 934 continue; 935 // The index of the first register to be used 936 unsigned RegIdx = RegLastIdx + TotalBytes; 937 RegLastIdx = RegIdx; 938 // If there are not enough registers, use the stack 939 if (RegIdx >= array_lengthof(RegList8)) { 940 UseStack = true; 941 } 942 for (; i != j; ++i) { 943 MVT VT = Args[i].VT; 944 945 if (UseStack) { 946 auto evt = EVT(VT).getTypeForEVT(CCInfo.getContext()); 947 unsigned Offset = CCInfo.AllocateStack(TD->getTypeAllocSize(evt), 948 TD->getABITypeAlign(evt)); 949 CCInfo.addLoc( 950 CCValAssign::getMem(i, VT, Offset, VT, CCValAssign::Full)); 951 } else { 952 unsigned Reg; 953 if (VT == MVT::i8) { 954 Reg = CCInfo.AllocateReg(RegList8[RegIdx]); 955 } else if (VT == MVT::i16) { 956 Reg = CCInfo.AllocateReg(RegList16[RegIdx]); 957 } else { 958 llvm_unreachable( 959 "calling convention can only manage i8 and i16 types"); 960 } 961 assert(Reg && "register not available in calling convention"); 962 CCInfo.addLoc(CCValAssign::getReg(i, VT, Reg, VT, CCValAssign::Full)); 963 // Registers inside a particular argument are sorted in increasing order 964 // (remember the array is reversed). 965 RegIdx -= VT.getStoreSize(); 966 } 967 } 968 } 969 } 970 971 /// Count the total number of bytes needed to pass or return these arguments. 972 template <typename ArgT> 973 static unsigned getTotalArgumentsSizeInBytes(const SmallVectorImpl<ArgT> &Args) { 974 unsigned TotalBytes = 0; 975 976 for (const ArgT& Arg : Args) { 977 TotalBytes += Arg.VT.getStoreSize(); 978 } 979 return TotalBytes; 980 } 981 982 /// Analyze incoming and outgoing value of returning from a function. 983 /// The algorithm is similar to analyzeArguments, but there can only be 984 /// one value, possibly an aggregate, and it is limited to 8 bytes. 985 template <typename ArgT> 986 static void analyzeReturnValues(const SmallVectorImpl<ArgT> &Args, 987 CCState &CCInfo) { 988 unsigned NumArgs = Args.size(); 989 unsigned TotalBytes = getTotalArgumentsSizeInBytes(Args); 990 // CanLowerReturn() guarantees this assertion. 991 assert(TotalBytes <= 8 && "return values greater than 8 bytes cannot be lowered"); 992 993 // GCC-ABI says that the size is rounded up to the next even number, 994 // but actually once it is more than 4 it will always round up to 8. 995 if (TotalBytes > 4) { 996 TotalBytes = 8; 997 } else { 998 TotalBytes = alignTo(TotalBytes, 2); 999 } 1000 1001 // The index of the first register to use. 1002 int RegIdx = TotalBytes - 1; 1003 for (unsigned i = 0; i != NumArgs; ++i) { 1004 MVT VT = Args[i].VT; 1005 unsigned Reg; 1006 if (VT == MVT::i8) { 1007 Reg = CCInfo.AllocateReg(RegList8[RegIdx]); 1008 } else if (VT == MVT::i16) { 1009 Reg = CCInfo.AllocateReg(RegList16[RegIdx]); 1010 } else { 1011 llvm_unreachable("calling convention can only manage i8 and i16 types"); 1012 } 1013 assert(Reg && "register not available in calling convention"); 1014 CCInfo.addLoc(CCValAssign::getReg(i, VT, Reg, VT, CCValAssign::Full)); 1015 // Registers sort in increasing order 1016 RegIdx -= VT.getStoreSize(); 1017 } 1018 } 1019 1020 SDValue AVRTargetLowering::LowerFormalArguments( 1021 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 1022 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1023 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 1024 MachineFunction &MF = DAG.getMachineFunction(); 1025 MachineFrameInfo &MFI = MF.getFrameInfo(); 1026 auto DL = DAG.getDataLayout(); 1027 1028 // Assign locations to all of the incoming arguments. 1029 SmallVector<CCValAssign, 16> ArgLocs; 1030 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1031 *DAG.getContext()); 1032 1033 // Variadic functions do not need all the analysis below. 1034 if (isVarArg) { 1035 CCInfo.AnalyzeFormalArguments(Ins, ArgCC_AVR_Vararg); 1036 } else { 1037 analyzeArguments(nullptr, &MF.getFunction(), &DL, Ins, ArgLocs, CCInfo); 1038 } 1039 1040 SDValue ArgValue; 1041 for (CCValAssign &VA : ArgLocs) { 1042 1043 // Arguments stored on registers. 1044 if (VA.isRegLoc()) { 1045 EVT RegVT = VA.getLocVT(); 1046 const TargetRegisterClass *RC; 1047 if (RegVT == MVT::i8) { 1048 RC = &AVR::GPR8RegClass; 1049 } else if (RegVT == MVT::i16) { 1050 RC = &AVR::DREGSRegClass; 1051 } else { 1052 llvm_unreachable("Unknown argument type!"); 1053 } 1054 1055 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 1056 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 1057 1058 // :NOTE: Clang should not promote any i8 into i16 but for safety the 1059 // following code will handle zexts or sexts generated by other 1060 // front ends. Otherwise: 1061 // If this is an 8 bit value, it is really passed promoted 1062 // to 16 bits. Insert an assert[sz]ext to capture this, then 1063 // truncate to the right size. 1064 switch (VA.getLocInfo()) { 1065 default: 1066 llvm_unreachable("Unknown loc info!"); 1067 case CCValAssign::Full: 1068 break; 1069 case CCValAssign::BCvt: 1070 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 1071 break; 1072 case CCValAssign::SExt: 1073 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 1074 DAG.getValueType(VA.getValVT())); 1075 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 1076 break; 1077 case CCValAssign::ZExt: 1078 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 1079 DAG.getValueType(VA.getValVT())); 1080 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 1081 break; 1082 } 1083 1084 InVals.push_back(ArgValue); 1085 } else { 1086 // Sanity check. 1087 assert(VA.isMemLoc()); 1088 1089 EVT LocVT = VA.getLocVT(); 1090 1091 // Create the frame index object for this incoming parameter. 1092 int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8, 1093 VA.getLocMemOffset(), true); 1094 1095 // Create the SelectionDAG nodes corresponding to a load 1096 // from this parameter. 1097 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DL)); 1098 InVals.push_back(DAG.getLoad(LocVT, dl, Chain, FIN, 1099 MachinePointerInfo::getFixedStack(MF, FI))); 1100 } 1101 } 1102 1103 // If the function takes variable number of arguments, make a frame index for 1104 // the start of the first vararg value... for expansion of llvm.va_start. 1105 if (isVarArg) { 1106 unsigned StackSize = CCInfo.getNextStackOffset(); 1107 AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>(); 1108 1109 AFI->setVarArgsFrameIndex(MFI.CreateFixedObject(2, StackSize, true)); 1110 } 1111 1112 return Chain; 1113 } 1114 1115 //===----------------------------------------------------------------------===// 1116 // Call Calling Convention Implementation 1117 //===----------------------------------------------------------------------===// 1118 1119 SDValue AVRTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1120 SmallVectorImpl<SDValue> &InVals) const { 1121 SelectionDAG &DAG = CLI.DAG; 1122 SDLoc &DL = CLI.DL; 1123 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1124 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1125 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1126 SDValue Chain = CLI.Chain; 1127 SDValue Callee = CLI.Callee; 1128 bool &isTailCall = CLI.IsTailCall; 1129 CallingConv::ID CallConv = CLI.CallConv; 1130 bool isVarArg = CLI.IsVarArg; 1131 1132 MachineFunction &MF = DAG.getMachineFunction(); 1133 1134 // AVR does not yet support tail call optimization. 1135 isTailCall = false; 1136 1137 // Analyze operands of the call, assigning locations to each operand. 1138 SmallVector<CCValAssign, 16> ArgLocs; 1139 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1140 *DAG.getContext()); 1141 1142 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1143 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1144 // node so that legalize doesn't hack it. 1145 const Function *F = nullptr; 1146 if (const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1147 const GlobalValue *GV = G->getGlobal(); 1148 1149 F = cast<Function>(GV); 1150 Callee = 1151 DAG.getTargetGlobalAddress(GV, DL, getPointerTy(DAG.getDataLayout())); 1152 } else if (const ExternalSymbolSDNode *ES = 1153 dyn_cast<ExternalSymbolSDNode>(Callee)) { 1154 Callee = DAG.getTargetExternalSymbol(ES->getSymbol(), 1155 getPointerTy(DAG.getDataLayout())); 1156 } 1157 1158 // Variadic functions do not need all the analysis below. 1159 if (isVarArg) { 1160 CCInfo.AnalyzeCallOperands(Outs, ArgCC_AVR_Vararg); 1161 } else { 1162 analyzeArguments(&CLI, F, &DAG.getDataLayout(), Outs, ArgLocs, CCInfo); 1163 } 1164 1165 // Get a count of how many bytes are to be pushed on the stack. 1166 unsigned NumBytes = CCInfo.getNextStackOffset(); 1167 1168 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL); 1169 1170 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 1171 1172 // First, walk the register assignments, inserting copies. 1173 unsigned AI, AE; 1174 bool HasStackArgs = false; 1175 for (AI = 0, AE = ArgLocs.size(); AI != AE; ++AI) { 1176 CCValAssign &VA = ArgLocs[AI]; 1177 EVT RegVT = VA.getLocVT(); 1178 SDValue Arg = OutVals[AI]; 1179 1180 // Promote the value if needed. With Clang this should not happen. 1181 switch (VA.getLocInfo()) { 1182 default: 1183 llvm_unreachable("Unknown loc info!"); 1184 case CCValAssign::Full: 1185 break; 1186 case CCValAssign::SExt: 1187 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, RegVT, Arg); 1188 break; 1189 case CCValAssign::ZExt: 1190 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, RegVT, Arg); 1191 break; 1192 case CCValAssign::AExt: 1193 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, RegVT, Arg); 1194 break; 1195 case CCValAssign::BCvt: 1196 Arg = DAG.getNode(ISD::BITCAST, DL, RegVT, Arg); 1197 break; 1198 } 1199 1200 // Stop when we encounter a stack argument, we need to process them 1201 // in reverse order in the loop below. 1202 if (VA.isMemLoc()) { 1203 HasStackArgs = true; 1204 break; 1205 } 1206 1207 // Arguments that can be passed on registers must be kept in the RegsToPass 1208 // vector. 1209 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1210 } 1211 1212 // Second, stack arguments have to walked in reverse order by inserting 1213 // chained stores, this ensures their order is not changed by the scheduler 1214 // and that the push instruction sequence generated is correct, otherwise they 1215 // can be freely intermixed. 1216 if (HasStackArgs) { 1217 for (AE = AI, AI = ArgLocs.size(); AI != AE; --AI) { 1218 unsigned Loc = AI - 1; 1219 CCValAssign &VA = ArgLocs[Loc]; 1220 SDValue Arg = OutVals[Loc]; 1221 1222 assert(VA.isMemLoc()); 1223 1224 // SP points to one stack slot further so add one to adjust it. 1225 SDValue PtrOff = DAG.getNode( 1226 ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), 1227 DAG.getRegister(AVR::SP, getPointerTy(DAG.getDataLayout())), 1228 DAG.getIntPtrConstant(VA.getLocMemOffset() + 1, DL)); 1229 1230 Chain = 1231 DAG.getStore(Chain, DL, Arg, PtrOff, 1232 MachinePointerInfo::getStack(MF, VA.getLocMemOffset())); 1233 } 1234 } 1235 1236 // Build a sequence of copy-to-reg nodes chained together with token chain and 1237 // flag operands which copy the outgoing args into registers. The InFlag in 1238 // necessary since all emited instructions must be stuck together. 1239 SDValue InFlag; 1240 for (auto Reg : RegsToPass) { 1241 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, InFlag); 1242 InFlag = Chain.getValue(1); 1243 } 1244 1245 // Returns a chain & a flag for retval copy to use. 1246 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 1247 SmallVector<SDValue, 8> Ops; 1248 Ops.push_back(Chain); 1249 Ops.push_back(Callee); 1250 1251 // Add argument registers to the end of the list so that they are known live 1252 // into the call. 1253 for (auto Reg : RegsToPass) { 1254 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 1255 } 1256 1257 // Add a register mask operand representing the call-preserved registers. 1258 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 1259 const uint32_t *Mask = 1260 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 1261 assert(Mask && "Missing call preserved mask for calling convention"); 1262 Ops.push_back(DAG.getRegisterMask(Mask)); 1263 1264 if (InFlag.getNode()) { 1265 Ops.push_back(InFlag); 1266 } 1267 1268 Chain = DAG.getNode(AVRISD::CALL, DL, NodeTys, Ops); 1269 InFlag = Chain.getValue(1); 1270 1271 // Create the CALLSEQ_END node. 1272 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 1273 DAG.getIntPtrConstant(0, DL, true), InFlag, DL); 1274 1275 if (!Ins.empty()) { 1276 InFlag = Chain.getValue(1); 1277 } 1278 1279 // Handle result values, copying them out of physregs into vregs that we 1280 // return. 1281 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, DL, DAG, 1282 InVals); 1283 } 1284 1285 /// Lower the result values of a call into the 1286 /// appropriate copies out of appropriate physical registers. 1287 /// 1288 SDValue AVRTargetLowering::LowerCallResult( 1289 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1290 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, SelectionDAG &DAG, 1291 SmallVectorImpl<SDValue> &InVals) const { 1292 1293 // Assign locations to each value returned by this call. 1294 SmallVector<CCValAssign, 16> RVLocs; 1295 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1296 *DAG.getContext()); 1297 1298 // Handle runtime calling convs. 1299 if (CallConv == CallingConv::AVR_BUILTIN) { 1300 CCInfo.AnalyzeCallResult(Ins, RetCC_AVR_BUILTIN); 1301 } else { 1302 analyzeReturnValues(Ins, CCInfo); 1303 } 1304 1305 // Copy all of the result registers out of their specified physreg. 1306 for (CCValAssign const &RVLoc : RVLocs) { 1307 Chain = DAG.getCopyFromReg(Chain, dl, RVLoc.getLocReg(), RVLoc.getValVT(), 1308 InFlag) 1309 .getValue(1); 1310 InFlag = Chain.getValue(2); 1311 InVals.push_back(Chain.getValue(0)); 1312 } 1313 1314 return Chain; 1315 } 1316 1317 //===----------------------------------------------------------------------===// 1318 // Return Value Calling Convention Implementation 1319 //===----------------------------------------------------------------------===// 1320 1321 bool AVRTargetLowering::CanLowerReturn( 1322 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, 1323 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 1324 if (CallConv == CallingConv::AVR_BUILTIN) { 1325 SmallVector<CCValAssign, 16> RVLocs; 1326 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 1327 return CCInfo.CheckReturn(Outs, RetCC_AVR_BUILTIN); 1328 } 1329 1330 unsigned TotalBytes = getTotalArgumentsSizeInBytes(Outs); 1331 return TotalBytes <= 8; 1332 } 1333 1334 SDValue 1335 AVRTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 1336 bool isVarArg, 1337 const SmallVectorImpl<ISD::OutputArg> &Outs, 1338 const SmallVectorImpl<SDValue> &OutVals, 1339 const SDLoc &dl, SelectionDAG &DAG) const { 1340 // CCValAssign - represent the assignment of the return value to locations. 1341 SmallVector<CCValAssign, 16> RVLocs; 1342 1343 // CCState - Info about the registers and stack slot. 1344 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1345 *DAG.getContext()); 1346 1347 MachineFunction &MF = DAG.getMachineFunction(); 1348 1349 // Analyze return values. 1350 if (CallConv == CallingConv::AVR_BUILTIN) { 1351 CCInfo.AnalyzeReturn(Outs, RetCC_AVR_BUILTIN); 1352 } else { 1353 analyzeReturnValues(Outs, CCInfo); 1354 } 1355 1356 SDValue Flag; 1357 SmallVector<SDValue, 4> RetOps(1, Chain); 1358 // Copy the result values into the output registers. 1359 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 1360 CCValAssign &VA = RVLocs[i]; 1361 assert(VA.isRegLoc() && "Can only return in registers!"); 1362 1363 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag); 1364 1365 // Guarantee that all emitted copies are stuck together with flags. 1366 Flag = Chain.getValue(1); 1367 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 1368 } 1369 1370 // Don't emit the ret/reti instruction when the naked attribute is present in 1371 // the function being compiled. 1372 if (MF.getFunction().getAttributes().hasAttribute( 1373 AttributeList::FunctionIndex, Attribute::Naked)) { 1374 return Chain; 1375 } 1376 1377 const AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>(); 1378 1379 unsigned RetOpc = 1380 AFI->isInterruptOrSignalHandler() 1381 ? AVRISD::RETI_FLAG 1382 : AVRISD::RET_FLAG; 1383 1384 RetOps[0] = Chain; // Update chain. 1385 1386 if (Flag.getNode()) { 1387 RetOps.push_back(Flag); 1388 } 1389 1390 return DAG.getNode(RetOpc, dl, MVT::Other, RetOps); 1391 } 1392 1393 //===----------------------------------------------------------------------===// 1394 // Custom Inserters 1395 //===----------------------------------------------------------------------===// 1396 1397 MachineBasicBlock *AVRTargetLowering::insertShift(MachineInstr &MI, 1398 MachineBasicBlock *BB) const { 1399 unsigned Opc; 1400 const TargetRegisterClass *RC; 1401 bool HasRepeatedOperand = false; 1402 MachineFunction *F = BB->getParent(); 1403 MachineRegisterInfo &RI = F->getRegInfo(); 1404 const TargetInstrInfo &TII = *Subtarget.getInstrInfo(); 1405 DebugLoc dl = MI.getDebugLoc(); 1406 1407 switch (MI.getOpcode()) { 1408 default: 1409 llvm_unreachable("Invalid shift opcode!"); 1410 case AVR::Lsl8: 1411 Opc = AVR::ADDRdRr; // LSL is an alias of ADD Rd, Rd 1412 RC = &AVR::GPR8RegClass; 1413 HasRepeatedOperand = true; 1414 break; 1415 case AVR::Lsl16: 1416 Opc = AVR::LSLWRd; 1417 RC = &AVR::DREGSRegClass; 1418 break; 1419 case AVR::Asr8: 1420 Opc = AVR::ASRRd; 1421 RC = &AVR::GPR8RegClass; 1422 break; 1423 case AVR::Asr16: 1424 Opc = AVR::ASRWRd; 1425 RC = &AVR::DREGSRegClass; 1426 break; 1427 case AVR::Lsr8: 1428 Opc = AVR::LSRRd; 1429 RC = &AVR::GPR8RegClass; 1430 break; 1431 case AVR::Lsr16: 1432 Opc = AVR::LSRWRd; 1433 RC = &AVR::DREGSRegClass; 1434 break; 1435 case AVR::Rol8: 1436 Opc = AVR::ROLBRd; 1437 RC = &AVR::GPR8RegClass; 1438 break; 1439 case AVR::Rol16: 1440 Opc = AVR::ROLWRd; 1441 RC = &AVR::DREGSRegClass; 1442 break; 1443 case AVR::Ror8: 1444 Opc = AVR::RORBRd; 1445 RC = &AVR::GPR8RegClass; 1446 break; 1447 case AVR::Ror16: 1448 Opc = AVR::RORWRd; 1449 RC = &AVR::DREGSRegClass; 1450 break; 1451 } 1452 1453 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 1454 1455 MachineFunction::iterator I; 1456 for (I = BB->getIterator(); I != F->end() && &(*I) != BB; ++I); 1457 if (I != F->end()) ++I; 1458 1459 // Create loop block. 1460 MachineBasicBlock *LoopBB = F->CreateMachineBasicBlock(LLVM_BB); 1461 MachineBasicBlock *CheckBB = F->CreateMachineBasicBlock(LLVM_BB); 1462 MachineBasicBlock *RemBB = F->CreateMachineBasicBlock(LLVM_BB); 1463 1464 F->insert(I, LoopBB); 1465 F->insert(I, CheckBB); 1466 F->insert(I, RemBB); 1467 1468 // Update machine-CFG edges by transferring all successors of the current 1469 // block to the block containing instructions after shift. 1470 RemBB->splice(RemBB->begin(), BB, std::next(MachineBasicBlock::iterator(MI)), 1471 BB->end()); 1472 RemBB->transferSuccessorsAndUpdatePHIs(BB); 1473 1474 // Add edges BB => LoopBB => CheckBB => RemBB, CheckBB => LoopBB. 1475 BB->addSuccessor(CheckBB); 1476 LoopBB->addSuccessor(CheckBB); 1477 CheckBB->addSuccessor(LoopBB); 1478 CheckBB->addSuccessor(RemBB); 1479 1480 Register ShiftAmtReg = RI.createVirtualRegister(&AVR::GPR8RegClass); 1481 Register ShiftAmtReg2 = RI.createVirtualRegister(&AVR::GPR8RegClass); 1482 Register ShiftReg = RI.createVirtualRegister(RC); 1483 Register ShiftReg2 = RI.createVirtualRegister(RC); 1484 Register ShiftAmtSrcReg = MI.getOperand(2).getReg(); 1485 Register SrcReg = MI.getOperand(1).getReg(); 1486 Register DstReg = MI.getOperand(0).getReg(); 1487 1488 // BB: 1489 // rjmp CheckBB 1490 BuildMI(BB, dl, TII.get(AVR::RJMPk)).addMBB(CheckBB); 1491 1492 // LoopBB: 1493 // ShiftReg2 = shift ShiftReg 1494 auto ShiftMI = BuildMI(LoopBB, dl, TII.get(Opc), ShiftReg2).addReg(ShiftReg); 1495 if (HasRepeatedOperand) 1496 ShiftMI.addReg(ShiftReg); 1497 1498 // CheckBB: 1499 // ShiftReg = phi [%SrcReg, BB], [%ShiftReg2, LoopBB] 1500 // ShiftAmt = phi [%N, BB], [%ShiftAmt2, LoopBB] 1501 // DestReg = phi [%SrcReg, BB], [%ShiftReg, LoopBB] 1502 // ShiftAmt2 = ShiftAmt - 1; 1503 // if (ShiftAmt2 >= 0) goto LoopBB; 1504 BuildMI(CheckBB, dl, TII.get(AVR::PHI), ShiftReg) 1505 .addReg(SrcReg) 1506 .addMBB(BB) 1507 .addReg(ShiftReg2) 1508 .addMBB(LoopBB); 1509 BuildMI(CheckBB, dl, TII.get(AVR::PHI), ShiftAmtReg) 1510 .addReg(ShiftAmtSrcReg) 1511 .addMBB(BB) 1512 .addReg(ShiftAmtReg2) 1513 .addMBB(LoopBB); 1514 BuildMI(CheckBB, dl, TII.get(AVR::PHI), DstReg) 1515 .addReg(SrcReg) 1516 .addMBB(BB) 1517 .addReg(ShiftReg2) 1518 .addMBB(LoopBB); 1519 1520 BuildMI(CheckBB, dl, TII.get(AVR::DECRd), ShiftAmtReg2) 1521 .addReg(ShiftAmtReg); 1522 BuildMI(CheckBB, dl, TII.get(AVR::BRPLk)).addMBB(LoopBB); 1523 1524 MI.eraseFromParent(); // The pseudo instruction is gone now. 1525 return RemBB; 1526 } 1527 1528 static bool isCopyMulResult(MachineBasicBlock::iterator const &I) { 1529 if (I->getOpcode() == AVR::COPY) { 1530 Register SrcReg = I->getOperand(1).getReg(); 1531 return (SrcReg == AVR::R0 || SrcReg == AVR::R1); 1532 } 1533 1534 return false; 1535 } 1536 1537 // The mul instructions wreak havock on our zero_reg R1. We need to clear it 1538 // after the result has been evacuated. This is probably not the best way to do 1539 // it, but it works for now. 1540 MachineBasicBlock *AVRTargetLowering::insertMul(MachineInstr &MI, 1541 MachineBasicBlock *BB) const { 1542 const TargetInstrInfo &TII = *Subtarget.getInstrInfo(); 1543 MachineBasicBlock::iterator I(MI); 1544 ++I; // in any case insert *after* the mul instruction 1545 if (isCopyMulResult(I)) 1546 ++I; 1547 if (isCopyMulResult(I)) 1548 ++I; 1549 BuildMI(*BB, I, MI.getDebugLoc(), TII.get(AVR::EORRdRr), AVR::R1) 1550 .addReg(AVR::R1) 1551 .addReg(AVR::R1); 1552 return BB; 1553 } 1554 1555 MachineBasicBlock * 1556 AVRTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 1557 MachineBasicBlock *MBB) const { 1558 int Opc = MI.getOpcode(); 1559 1560 // Pseudo shift instructions with a non constant shift amount are expanded 1561 // into a loop. 1562 switch (Opc) { 1563 case AVR::Lsl8: 1564 case AVR::Lsl16: 1565 case AVR::Lsr8: 1566 case AVR::Lsr16: 1567 case AVR::Rol8: 1568 case AVR::Rol16: 1569 case AVR::Ror8: 1570 case AVR::Ror16: 1571 case AVR::Asr8: 1572 case AVR::Asr16: 1573 return insertShift(MI, MBB); 1574 case AVR::MULRdRr: 1575 case AVR::MULSRdRr: 1576 return insertMul(MI, MBB); 1577 } 1578 1579 assert((Opc == AVR::Select16 || Opc == AVR::Select8) && 1580 "Unexpected instr type to insert"); 1581 1582 const AVRInstrInfo &TII = (const AVRInstrInfo &)*MI.getParent() 1583 ->getParent() 1584 ->getSubtarget() 1585 .getInstrInfo(); 1586 DebugLoc dl = MI.getDebugLoc(); 1587 1588 // To "insert" a SELECT instruction, we insert the diamond 1589 // control-flow pattern. The incoming instruction knows the 1590 // destination vreg to set, the condition code register to branch 1591 // on, the true/false values to select between, and a branch opcode 1592 // to use. 1593 1594 MachineFunction *MF = MBB->getParent(); 1595 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 1596 MachineBasicBlock *FallThrough = MBB->getFallThrough(); 1597 1598 // If the current basic block falls through to another basic block, 1599 // we must insert an unconditional branch to the fallthrough destination 1600 // if we are to insert basic blocks at the prior fallthrough point. 1601 if (FallThrough != nullptr) { 1602 BuildMI(MBB, dl, TII.get(AVR::RJMPk)).addMBB(FallThrough); 1603 } 1604 1605 MachineBasicBlock *trueMBB = MF->CreateMachineBasicBlock(LLVM_BB); 1606 MachineBasicBlock *falseMBB = MF->CreateMachineBasicBlock(LLVM_BB); 1607 1608 MachineFunction::iterator I; 1609 for (I = MF->begin(); I != MF->end() && &(*I) != MBB; ++I); 1610 if (I != MF->end()) ++I; 1611 MF->insert(I, trueMBB); 1612 MF->insert(I, falseMBB); 1613 1614 // Transfer remaining instructions and all successors of the current 1615 // block to the block which will contain the Phi node for the 1616 // select. 1617 trueMBB->splice(trueMBB->begin(), MBB, 1618 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 1619 trueMBB->transferSuccessorsAndUpdatePHIs(MBB); 1620 1621 AVRCC::CondCodes CC = (AVRCC::CondCodes)MI.getOperand(3).getImm(); 1622 BuildMI(MBB, dl, TII.getBrCond(CC)).addMBB(trueMBB); 1623 BuildMI(MBB, dl, TII.get(AVR::RJMPk)).addMBB(falseMBB); 1624 MBB->addSuccessor(falseMBB); 1625 MBB->addSuccessor(trueMBB); 1626 1627 // Unconditionally flow back to the true block 1628 BuildMI(falseMBB, dl, TII.get(AVR::RJMPk)).addMBB(trueMBB); 1629 falseMBB->addSuccessor(trueMBB); 1630 1631 // Set up the Phi node to determine where we came from 1632 BuildMI(*trueMBB, trueMBB->begin(), dl, TII.get(AVR::PHI), MI.getOperand(0).getReg()) 1633 .addReg(MI.getOperand(1).getReg()) 1634 .addMBB(MBB) 1635 .addReg(MI.getOperand(2).getReg()) 1636 .addMBB(falseMBB) ; 1637 1638 MI.eraseFromParent(); // The pseudo instruction is gone now. 1639 return trueMBB; 1640 } 1641 1642 //===----------------------------------------------------------------------===// 1643 // Inline Asm Support 1644 //===----------------------------------------------------------------------===// 1645 1646 AVRTargetLowering::ConstraintType 1647 AVRTargetLowering::getConstraintType(StringRef Constraint) const { 1648 if (Constraint.size() == 1) { 1649 // See http://www.nongnu.org/avr-libc/user-manual/inline_asm.html 1650 switch (Constraint[0]) { 1651 default: 1652 break; 1653 case 'a': // Simple upper registers 1654 case 'b': // Base pointer registers pairs 1655 case 'd': // Upper register 1656 case 'l': // Lower registers 1657 case 'e': // Pointer register pairs 1658 case 'q': // Stack pointer register 1659 case 'r': // Any register 1660 case 'w': // Special upper register pairs 1661 return C_RegisterClass; 1662 case 't': // Temporary register 1663 case 'x': case 'X': // Pointer register pair X 1664 case 'y': case 'Y': // Pointer register pair Y 1665 case 'z': case 'Z': // Pointer register pair Z 1666 return C_Register; 1667 case 'Q': // A memory address based on Y or Z pointer with displacement. 1668 return C_Memory; 1669 case 'G': // Floating point constant 1670 case 'I': // 6-bit positive integer constant 1671 case 'J': // 6-bit negative integer constant 1672 case 'K': // Integer constant (Range: 2) 1673 case 'L': // Integer constant (Range: 0) 1674 case 'M': // 8-bit integer constant 1675 case 'N': // Integer constant (Range: -1) 1676 case 'O': // Integer constant (Range: 8, 16, 24) 1677 case 'P': // Integer constant (Range: 1) 1678 case 'R': // Integer constant (Range: -6 to 5)x 1679 return C_Immediate; 1680 } 1681 } 1682 1683 return TargetLowering::getConstraintType(Constraint); 1684 } 1685 1686 unsigned 1687 AVRTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 1688 // Not sure if this is actually the right thing to do, but we got to do 1689 // *something* [agnat] 1690 switch (ConstraintCode[0]) { 1691 case 'Q': 1692 return InlineAsm::Constraint_Q; 1693 } 1694 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 1695 } 1696 1697 AVRTargetLowering::ConstraintWeight 1698 AVRTargetLowering::getSingleConstraintMatchWeight( 1699 AsmOperandInfo &info, const char *constraint) const { 1700 ConstraintWeight weight = CW_Invalid; 1701 Value *CallOperandVal = info.CallOperandVal; 1702 1703 // If we don't have a value, we can't do a match, 1704 // but allow it at the lowest weight. 1705 // (this behaviour has been copied from the ARM backend) 1706 if (!CallOperandVal) { 1707 return CW_Default; 1708 } 1709 1710 // Look at the constraint type. 1711 switch (*constraint) { 1712 default: 1713 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 1714 break; 1715 case 'd': 1716 case 'r': 1717 case 'l': 1718 weight = CW_Register; 1719 break; 1720 case 'a': 1721 case 'b': 1722 case 'e': 1723 case 'q': 1724 case 't': 1725 case 'w': 1726 case 'x': case 'X': 1727 case 'y': case 'Y': 1728 case 'z': case 'Z': 1729 weight = CW_SpecificReg; 1730 break; 1731 case 'G': 1732 if (const ConstantFP *C = dyn_cast<ConstantFP>(CallOperandVal)) { 1733 if (C->isZero()) { 1734 weight = CW_Constant; 1735 } 1736 } 1737 break; 1738 case 'I': 1739 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 1740 if (isUInt<6>(C->getZExtValue())) { 1741 weight = CW_Constant; 1742 } 1743 } 1744 break; 1745 case 'J': 1746 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 1747 if ((C->getSExtValue() >= -63) && (C->getSExtValue() <= 0)) { 1748 weight = CW_Constant; 1749 } 1750 } 1751 break; 1752 case 'K': 1753 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 1754 if (C->getZExtValue() == 2) { 1755 weight = CW_Constant; 1756 } 1757 } 1758 break; 1759 case 'L': 1760 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 1761 if (C->getZExtValue() == 0) { 1762 weight = CW_Constant; 1763 } 1764 } 1765 break; 1766 case 'M': 1767 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 1768 if (isUInt<8>(C->getZExtValue())) { 1769 weight = CW_Constant; 1770 } 1771 } 1772 break; 1773 case 'N': 1774 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 1775 if (C->getSExtValue() == -1) { 1776 weight = CW_Constant; 1777 } 1778 } 1779 break; 1780 case 'O': 1781 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 1782 if ((C->getZExtValue() == 8) || (C->getZExtValue() == 16) || 1783 (C->getZExtValue() == 24)) { 1784 weight = CW_Constant; 1785 } 1786 } 1787 break; 1788 case 'P': 1789 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 1790 if (C->getZExtValue() == 1) { 1791 weight = CW_Constant; 1792 } 1793 } 1794 break; 1795 case 'R': 1796 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 1797 if ((C->getSExtValue() >= -6) && (C->getSExtValue() <= 5)) { 1798 weight = CW_Constant; 1799 } 1800 } 1801 break; 1802 case 'Q': 1803 weight = CW_Memory; 1804 break; 1805 } 1806 1807 return weight; 1808 } 1809 1810 std::pair<unsigned, const TargetRegisterClass *> 1811 AVRTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 1812 StringRef Constraint, 1813 MVT VT) const { 1814 // We only support i8 and i16. 1815 // 1816 //:FIXME: remove this assert for now since it gets sometimes executed 1817 // assert((VT == MVT::i16 || VT == MVT::i8) && "Wrong operand type."); 1818 1819 if (Constraint.size() == 1) { 1820 switch (Constraint[0]) { 1821 case 'a': // Simple upper registers r16..r23. 1822 return std::make_pair(0U, &AVR::LD8loRegClass); 1823 case 'b': // Base pointer registers: y, z. 1824 return std::make_pair(0U, &AVR::PTRDISPREGSRegClass); 1825 case 'd': // Upper registers r16..r31. 1826 return std::make_pair(0U, &AVR::LD8RegClass); 1827 case 'l': // Lower registers r0..r15. 1828 return std::make_pair(0U, &AVR::GPR8loRegClass); 1829 case 'e': // Pointer register pairs: x, y, z. 1830 return std::make_pair(0U, &AVR::PTRREGSRegClass); 1831 case 'q': // Stack pointer register: SPH:SPL. 1832 return std::make_pair(0U, &AVR::GPRSPRegClass); 1833 case 'r': // Any register: r0..r31. 1834 if (VT == MVT::i8) 1835 return std::make_pair(0U, &AVR::GPR8RegClass); 1836 1837 assert(VT == MVT::i16 && "inline asm constraint too large"); 1838 return std::make_pair(0U, &AVR::DREGSRegClass); 1839 case 't': // Temporary register: r0. 1840 return std::make_pair(unsigned(AVR::R0), &AVR::GPR8RegClass); 1841 case 'w': // Special upper register pairs: r24, r26, r28, r30. 1842 return std::make_pair(0U, &AVR::IWREGSRegClass); 1843 case 'x': // Pointer register pair X: r27:r26. 1844 case 'X': 1845 return std::make_pair(unsigned(AVR::R27R26), &AVR::PTRREGSRegClass); 1846 case 'y': // Pointer register pair Y: r29:r28. 1847 case 'Y': 1848 return std::make_pair(unsigned(AVR::R29R28), &AVR::PTRREGSRegClass); 1849 case 'z': // Pointer register pair Z: r31:r30. 1850 case 'Z': 1851 return std::make_pair(unsigned(AVR::R31R30), &AVR::PTRREGSRegClass); 1852 default: 1853 break; 1854 } 1855 } 1856 1857 return TargetLowering::getRegForInlineAsmConstraint( 1858 Subtarget.getRegisterInfo(), Constraint, VT); 1859 } 1860 1861 void AVRTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 1862 std::string &Constraint, 1863 std::vector<SDValue> &Ops, 1864 SelectionDAG &DAG) const { 1865 SDValue Result(0, 0); 1866 SDLoc DL(Op); 1867 EVT Ty = Op.getValueType(); 1868 1869 // Currently only support length 1 constraints. 1870 if (Constraint.length() != 1) { 1871 return; 1872 } 1873 1874 char ConstraintLetter = Constraint[0]; 1875 switch (ConstraintLetter) { 1876 default: 1877 break; 1878 // Deal with integers first: 1879 case 'I': 1880 case 'J': 1881 case 'K': 1882 case 'L': 1883 case 'M': 1884 case 'N': 1885 case 'O': 1886 case 'P': 1887 case 'R': { 1888 const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 1889 if (!C) { 1890 return; 1891 } 1892 1893 int64_t CVal64 = C->getSExtValue(); 1894 uint64_t CUVal64 = C->getZExtValue(); 1895 switch (ConstraintLetter) { 1896 case 'I': // 0..63 1897 if (!isUInt<6>(CUVal64)) 1898 return; 1899 Result = DAG.getTargetConstant(CUVal64, DL, Ty); 1900 break; 1901 case 'J': // -63..0 1902 if (CVal64 < -63 || CVal64 > 0) 1903 return; 1904 Result = DAG.getTargetConstant(CVal64, DL, Ty); 1905 break; 1906 case 'K': // 2 1907 if (CUVal64 != 2) 1908 return; 1909 Result = DAG.getTargetConstant(CUVal64, DL, Ty); 1910 break; 1911 case 'L': // 0 1912 if (CUVal64 != 0) 1913 return; 1914 Result = DAG.getTargetConstant(CUVal64, DL, Ty); 1915 break; 1916 case 'M': // 0..255 1917 if (!isUInt<8>(CUVal64)) 1918 return; 1919 // i8 type may be printed as a negative number, 1920 // e.g. 254 would be printed as -2, 1921 // so we force it to i16 at least. 1922 if (Ty.getSimpleVT() == MVT::i8) { 1923 Ty = MVT::i16; 1924 } 1925 Result = DAG.getTargetConstant(CUVal64, DL, Ty); 1926 break; 1927 case 'N': // -1 1928 if (CVal64 != -1) 1929 return; 1930 Result = DAG.getTargetConstant(CVal64, DL, Ty); 1931 break; 1932 case 'O': // 8, 16, 24 1933 if (CUVal64 != 8 && CUVal64 != 16 && CUVal64 != 24) 1934 return; 1935 Result = DAG.getTargetConstant(CUVal64, DL, Ty); 1936 break; 1937 case 'P': // 1 1938 if (CUVal64 != 1) 1939 return; 1940 Result = DAG.getTargetConstant(CUVal64, DL, Ty); 1941 break; 1942 case 'R': // -6..5 1943 if (CVal64 < -6 || CVal64 > 5) 1944 return; 1945 Result = DAG.getTargetConstant(CVal64, DL, Ty); 1946 break; 1947 } 1948 1949 break; 1950 } 1951 case 'G': 1952 const ConstantFPSDNode *FC = dyn_cast<ConstantFPSDNode>(Op); 1953 if (!FC || !FC->isZero()) 1954 return; 1955 // Soften float to i8 0 1956 Result = DAG.getTargetConstant(0, DL, MVT::i8); 1957 break; 1958 } 1959 1960 if (Result.getNode()) { 1961 Ops.push_back(Result); 1962 return; 1963 } 1964 1965 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 1966 } 1967 1968 Register AVRTargetLowering::getRegisterByName(const char *RegName, LLT VT, 1969 const MachineFunction &MF) const { 1970 Register Reg; 1971 1972 if (VT == LLT::scalar(8)) { 1973 Reg = StringSwitch<unsigned>(RegName) 1974 .Case("r0", AVR::R0).Case("r1", AVR::R1).Case("r2", AVR::R2) 1975 .Case("r3", AVR::R3).Case("r4", AVR::R4).Case("r5", AVR::R5) 1976 .Case("r6", AVR::R6).Case("r7", AVR::R7).Case("r8", AVR::R8) 1977 .Case("r9", AVR::R9).Case("r10", AVR::R10).Case("r11", AVR::R11) 1978 .Case("r12", AVR::R12).Case("r13", AVR::R13).Case("r14", AVR::R14) 1979 .Case("r15", AVR::R15).Case("r16", AVR::R16).Case("r17", AVR::R17) 1980 .Case("r18", AVR::R18).Case("r19", AVR::R19).Case("r20", AVR::R20) 1981 .Case("r21", AVR::R21).Case("r22", AVR::R22).Case("r23", AVR::R23) 1982 .Case("r24", AVR::R24).Case("r25", AVR::R25).Case("r26", AVR::R26) 1983 .Case("r27", AVR::R27).Case("r28", AVR::R28).Case("r29", AVR::R29) 1984 .Case("r30", AVR::R30).Case("r31", AVR::R31) 1985 .Case("X", AVR::R27R26).Case("Y", AVR::R29R28).Case("Z", AVR::R31R30) 1986 .Default(0); 1987 } else { 1988 Reg = StringSwitch<unsigned>(RegName) 1989 .Case("r0", AVR::R1R0).Case("r2", AVR::R3R2) 1990 .Case("r4", AVR::R5R4).Case("r6", AVR::R7R6) 1991 .Case("r8", AVR::R9R8).Case("r10", AVR::R11R10) 1992 .Case("r12", AVR::R13R12).Case("r14", AVR::R15R14) 1993 .Case("r16", AVR::R17R16).Case("r18", AVR::R19R18) 1994 .Case("r20", AVR::R21R20).Case("r22", AVR::R23R22) 1995 .Case("r24", AVR::R25R24).Case("r26", AVR::R27R26) 1996 .Case("r28", AVR::R29R28).Case("r30", AVR::R31R30) 1997 .Case("X", AVR::R27R26).Case("Y", AVR::R29R28).Case("Z", AVR::R31R30) 1998 .Default(0); 1999 } 2000 2001 if (Reg) 2002 return Reg; 2003 2004 report_fatal_error("Invalid register name global variable"); 2005 } 2006 2007 } // end of namespace llvm 2008