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