LLVM 24.0.0git
AVRISelLowering.cpp
Go to the documentation of this file.
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/ArrayRef.h"
24#include "llvm/IR/Function.h"
26
27#include "AVR.h"
29#include "AVRSubtarget.h"
30#include "AVRTargetMachine.h"
32
33namespace llvm {
34
36 const AVRSubtarget &STI)
37 : TargetLowering(TM, STI), 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
51
56
61
63
64 for (MVT VT : MVT::integer_valuetypes()) {
65 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) {
66 setLoadExtAction(N, VT, MVT::i1, Promote);
67 setLoadExtAction(N, VT, MVT::i8, Expand);
68 }
69 }
70
71 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
72
73 for (MVT VT : MVT::integer_valuetypes()) {
78 }
79
80 // sub (x, imm) gets canonicalized to add (x, -imm), so for illegal types
81 // revert into a sub since we don't have an add with immediate instruction.
84
85 // our shift instructions are only able to shift 1 bit at a time, so handle
86 // this in a custom way.
99
104
110
121
123
124 // Add support for postincrement and predecrement load/stores.
133
135
140
141 // Atomic operations which must be lowered to rtlib calls
142 for (MVT VT : MVT::integer_valuetypes()) {
150 }
151
152 // Division/remainder
161
162 // Make division and modulus custom
169
170 // Do not use MUL. The AVR instructions are closer to SMUL_LOHI &co.
173
174 // Expand 16 bit multiplications.
177
178 // Expand multiplications to libcalls when there is
179 // no hardware MUL.
180 if (!Subtarget.supportsMultiplication()) {
183 }
184
185 for (MVT VT : MVT::integer_valuetypes()) {
188 }
189
190 for (MVT VT : MVT::integer_valuetypes()) {
194 }
195
196 for (MVT VT : MVT::integer_valuetypes()) {
198 // TODO: The generated code is pretty poor. Investigate using the
199 // same "shift and subtract with carry" trick that we do for
200 // extending 8-bit to 16-bit. This may require infrastructure
201 // improvements in how we treat 16-bit "registers" to be feasible.
202 }
203
206}
207
209 EVT VT) const {
210 assert(!VT.isVector() && "No AVR SetCC type for vectors!");
211 return MVT::i8;
212}
213
214SDValue AVRTargetLowering::LowerShifts(SDValue Op, SelectionDAG &DAG) const {
215 unsigned Opc8;
216 const SDNode *N = Op.getNode();
217 EVT VT = Op.getValueType();
218 SDLoc dl(N);
220 "Expected power-of-2 shift amount");
221
222 if (VT.getSizeInBits() == 32) {
223 if (!isa<ConstantSDNode>(N->getOperand(1))) {
224 // 32-bit shifts are converted to a loop in IR.
225 // This should be unreachable.
226 report_fatal_error("Expected a constant shift amount!");
227 }
228 SDVTList ResTys = DAG.getVTList(MVT::i16, MVT::i16);
229 SDValue SrcLo =
230 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i16, Op.getOperand(0),
231 DAG.getConstant(0, dl, MVT::i16));
232 SDValue SrcHi =
233 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i16, Op.getOperand(0),
234 DAG.getConstant(1, dl, MVT::i16));
235 uint64_t ShiftAmount = N->getConstantOperandVal(1);
236 if (ShiftAmount == 16) {
237 // Special case these two operations because they appear to be used by the
238 // generic codegen parts to lower 32-bit numbers.
239 // TODO: Perhaps we can lower shift amounts bigger than 16 to a 16-bit
240 // shift of a part of the 32-bit value?
241 switch (Op.getOpcode()) {
242 case ISD::SHL: {
243 SDValue Zero = DAG.getConstant(0, dl, MVT::i16);
244 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i32, Zero, SrcLo);
245 }
246 case ISD::SRL: {
247 SDValue Zero = DAG.getConstant(0, dl, MVT::i16);
248 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i32, SrcHi, Zero);
249 }
250 }
251 }
252 SDValue Cnt = DAG.getTargetConstant(ShiftAmount, dl, MVT::i8);
253 unsigned Opc;
254 switch (Op.getOpcode()) {
255 default:
256 llvm_unreachable("Invalid 32-bit shift opcode!");
257 case ISD::SHL:
258 Opc = AVRISD::LSLW;
259 break;
260 case ISD::SRL:
261 Opc = AVRISD::LSRW;
262 break;
263 case ISD::SRA:
264 Opc = AVRISD::ASRW;
265 break;
266 }
267 SDValue Result = DAG.getNode(Opc, dl, ResTys, SrcLo, SrcHi, Cnt);
268 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i32, Result.getValue(0),
269 Result.getValue(1));
270 }
271
272 // Expand non-constant shifts to loops.
273 if (!isa<ConstantSDNode>(N->getOperand(1))) {
274 switch (Op.getOpcode()) {
275 default:
276 llvm_unreachable("Invalid shift opcode!");
277 case ISD::SHL:
278 return DAG.getNode(AVRISD::LSLLOOP, dl, VT, N->getOperand(0),
279 N->getOperand(1));
280 case ISD::SRL:
281 return DAG.getNode(AVRISD::LSRLOOP, dl, VT, N->getOperand(0),
282 N->getOperand(1));
283 case ISD::ROTL: {
284 SDValue Amt = N->getOperand(1);
285 EVT AmtVT = Amt.getValueType();
286 Amt = DAG.getNode(ISD::AND, dl, AmtVT, Amt,
287 DAG.getConstant(VT.getSizeInBits() - 1, dl, AmtVT));
288 return DAG.getNode(AVRISD::ROLLOOP, dl, VT, N->getOperand(0), Amt);
289 }
290 case ISD::ROTR: {
291 SDValue Amt = N->getOperand(1);
292 EVT AmtVT = Amt.getValueType();
293 Amt = DAG.getNode(ISD::AND, dl, AmtVT, Amt,
294 DAG.getConstant(VT.getSizeInBits() - 1, dl, AmtVT));
295 return DAG.getNode(AVRISD::RORLOOP, dl, VT, N->getOperand(0), Amt);
296 }
297 case ISD::SRA:
298 return DAG.getNode(AVRISD::ASRLOOP, dl, VT, N->getOperand(0),
299 N->getOperand(1));
300 }
301 }
302
303 uint64_t ShiftAmount = N->getConstantOperandVal(1);
304 SDValue Victim = N->getOperand(0);
305
306 switch (Op.getOpcode()) {
307 case ISD::SRA:
308 Opc8 = AVRISD::ASR;
309 break;
310 case ISD::ROTL:
311 Opc8 = AVRISD::ROL;
312 ShiftAmount = ShiftAmount % VT.getSizeInBits();
313 break;
314 case ISD::ROTR:
315 Opc8 = AVRISD::ROR;
316 ShiftAmount = ShiftAmount % VT.getSizeInBits();
317 break;
318 case ISD::SRL:
319 Opc8 = AVRISD::LSR;
320 break;
321 case ISD::SHL:
322 Opc8 = AVRISD::LSL;
323 break;
324 default:
325 llvm_unreachable("Invalid shift opcode");
326 }
327
328 // Optimize int8/int16 shifts.
329 if (VT.getSizeInBits() == 8) {
330 if (Op.getOpcode() == ISD::SHL && 4 <= ShiftAmount && ShiftAmount < 7) {
331 // Optimize LSL when 4 <= ShiftAmount <= 6.
332 Victim = DAG.getNode(AVRISD::SWAP, dl, VT, Victim);
333 Victim =
334 DAG.getNode(ISD::AND, dl, VT, Victim, DAG.getConstant(0xf0, dl, VT));
335 ShiftAmount -= 4;
336 } else if (Op.getOpcode() == ISD::SRL && 4 <= ShiftAmount &&
337 ShiftAmount < 7) {
338 // Optimize LSR when 4 <= ShiftAmount <= 6.
339 Victim = DAG.getNode(AVRISD::SWAP, dl, VT, Victim);
340 Victim =
341 DAG.getNode(ISD::AND, dl, VT, Victim, DAG.getConstant(0x0f, dl, VT));
342 ShiftAmount -= 4;
343 } else if (Op.getOpcode() == ISD::SHL && ShiftAmount == 7) {
344 // Optimize LSL when ShiftAmount == 7.
345 Victim = DAG.getNode(AVRISD::LSLBN, dl, VT, Victim,
346 DAG.getConstant(7, dl, VT));
347 ShiftAmount = 0;
348 } else if (Op.getOpcode() == ISD::SRL && ShiftAmount == 7) {
349 // Optimize LSR when ShiftAmount == 7.
350 Victim = DAG.getNode(AVRISD::LSRBN, dl, VT, Victim,
351 DAG.getConstant(7, dl, VT));
352 ShiftAmount = 0;
353 } else if (Op.getOpcode() == ISD::SRA && ShiftAmount == 6) {
354 // Optimize ASR when ShiftAmount == 6.
355 Victim = DAG.getNode(AVRISD::ASRBN, dl, VT, Victim,
356 DAG.getConstant(6, dl, VT));
357 ShiftAmount = 0;
358 } else if (Op.getOpcode() == ISD::SRA && ShiftAmount == 7) {
359 // Optimize ASR when ShiftAmount == 7.
360 Victim = DAG.getNode(AVRISD::ASRBN, dl, VT, Victim,
361 DAG.getConstant(7, dl, VT));
362 ShiftAmount = 0;
363 } else if (Op.getOpcode() == ISD::ROTL && ShiftAmount == 3) {
364 // Optimize left rotation 3 bits to swap then right rotation 1 bit.
365 Victim = DAG.getNode(AVRISD::SWAP, dl, VT, Victim);
366 Victim = DAG.getNode(AVRISD::ROR, dl, VT, Victim);
367 ShiftAmount = 0;
368 } else if (Op.getOpcode() == ISD::ROTR && ShiftAmount == 3) {
369 // Optimize right rotation 3 bits to swap then left rotation 1 bit.
370 Victim = DAG.getNode(AVRISD::SWAP, dl, VT, Victim);
371 Victim = DAG.getNode(AVRISD::ROL, dl, VT, Victim);
372 ShiftAmount = 0;
373 } else if (Op.getOpcode() == ISD::ROTL && ShiftAmount == 7) {
374 // Optimize left rotation 7 bits to right rotation 1 bit.
375 Victim = DAG.getNode(AVRISD::ROR, dl, VT, Victim);
376 ShiftAmount = 0;
377 } else if (Op.getOpcode() == ISD::ROTR && ShiftAmount == 7) {
378 // Optimize right rotation 7 bits to left rotation 1 bit.
379 Victim = DAG.getNode(AVRISD::ROL, dl, VT, Victim);
380 ShiftAmount = 0;
381 } else if ((Op.getOpcode() == ISD::ROTR || Op.getOpcode() == ISD::ROTL) &&
382 ShiftAmount >= 4) {
383 // Optimize left/right rotation with the SWAP instruction.
384 Victim = DAG.getNode(AVRISD::SWAP, dl, VT, Victim);
385 ShiftAmount -= 4;
386 }
387 } else if (VT.getSizeInBits() == 16) {
388 if (Op.getOpcode() == ISD::SRA)
389 // Special optimization for int16 arithmetic right shift.
390 switch (ShiftAmount) {
391 case 15:
392 Victim = DAG.getNode(AVRISD::ASRWN, dl, VT, Victim,
393 DAG.getConstant(15, dl, VT));
394 ShiftAmount = 0;
395 break;
396 case 14:
397 Victim = DAG.getNode(AVRISD::ASRWN, dl, VT, Victim,
398 DAG.getConstant(14, dl, VT));
399 ShiftAmount = 0;
400 break;
401 case 7:
402 Victim = DAG.getNode(AVRISD::ASRWN, dl, VT, Victim,
403 DAG.getConstant(7, dl, VT));
404 ShiftAmount = 0;
405 break;
406 default:
407 break;
408 }
409 if (4 <= ShiftAmount && ShiftAmount < 8)
410 switch (Op.getOpcode()) {
411 case ISD::SHL:
412 Victim = DAG.getNode(AVRISD::LSLWN, dl, VT, Victim,
413 DAG.getConstant(4, dl, VT));
414 ShiftAmount -= 4;
415 break;
416 case ISD::SRL:
417 Victim = DAG.getNode(AVRISD::LSRWN, dl, VT, Victim,
418 DAG.getConstant(4, dl, VT));
419 ShiftAmount -= 4;
420 break;
421 default:
422 break;
423 }
424 else if (8 <= ShiftAmount && ShiftAmount < 12)
425 switch (Op.getOpcode()) {
426 case ISD::SHL:
427 Victim = DAG.getNode(AVRISD::LSLWN, dl, VT, Victim,
428 DAG.getConstant(8, dl, VT));
429 ShiftAmount -= 8;
430 // Only operate on the higher byte for remaining shift bits.
431 Opc8 = AVRISD::LSLHI;
432 break;
433 case ISD::SRL:
434 Victim = DAG.getNode(AVRISD::LSRWN, dl, VT, Victim,
435 DAG.getConstant(8, dl, VT));
436 ShiftAmount -= 8;
437 // Only operate on the lower byte for remaining shift bits.
438 Opc8 = AVRISD::LSRLO;
439 break;
440 case ISD::SRA:
441 Victim = DAG.getNode(AVRISD::ASRWN, dl, VT, Victim,
442 DAG.getConstant(8, dl, VT));
443 ShiftAmount -= 8;
444 // Only operate on the lower byte for remaining shift bits.
445 Opc8 = AVRISD::ASRLO;
446 break;
447 default:
448 break;
449 }
450 else if (12 <= ShiftAmount)
451 switch (Op.getOpcode()) {
452 case ISD::SHL:
453 Victim = DAG.getNode(AVRISD::LSLWN, dl, VT, Victim,
454 DAG.getConstant(12, dl, VT));
455 ShiftAmount -= 12;
456 // Only operate on the higher byte for remaining shift bits.
457 Opc8 = AVRISD::LSLHI;
458 break;
459 case ISD::SRL:
460 Victim = DAG.getNode(AVRISD::LSRWN, dl, VT, Victim,
461 DAG.getConstant(12, dl, VT));
462 ShiftAmount -= 12;
463 // Only operate on the lower byte for remaining shift bits.
464 Opc8 = AVRISD::LSRLO;
465 break;
466 case ISD::SRA:
467 Victim = DAG.getNode(AVRISD::ASRWN, dl, VT, Victim,
468 DAG.getConstant(8, dl, VT));
469 ShiftAmount -= 8;
470 // Only operate on the lower byte for remaining shift bits.
471 Opc8 = AVRISD::ASRLO;
472 break;
473 default:
474 break;
475 }
476 }
477
478 while (ShiftAmount--) {
479 Victim = DAG.getNode(Opc8, dl, VT, Victim);
480 }
481
482 return Victim;
483}
484
485SDValue AVRTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
486 unsigned Opcode = Op->getOpcode();
487 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
488 "Invalid opcode for Div/Rem lowering");
489 bool IsSigned = (Opcode == ISD::SDIVREM);
490 EVT VT = Op->getValueType(0);
491 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
492
493 RTLIB::Libcall LC;
494 switch (VT.getSimpleVT().SimpleTy) {
495 default:
496 llvm_unreachable("Unexpected request for libcall!");
497 case MVT::i8:
498 LC = IsSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8;
499 break;
500 case MVT::i16:
501 LC = IsSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16;
502 break;
503 case MVT::i32:
504 LC = IsSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32;
505 break;
506 }
507
508 SDValue InChain = DAG.getEntryNode();
509
511 for (SDValue const &Value : Op->op_values()) {
512 TargetLowering::ArgListEntry Entry(
513 Value, Value.getValueType().getTypeForEVT(*DAG.getContext()));
514 Entry.IsSExt = IsSigned;
515 Entry.IsZExt = !IsSigned;
516 Args.push_back(Entry);
517 }
518
519 RTLIB::LibcallImpl LCImpl = DAG.getLibcalls().getLibcallImpl(LC);
520 if (LCImpl == RTLIB::Unsupported)
521 return SDValue();
522
524 DAG.getExternalSymbol(LCImpl, getPointerTy(DAG.getDataLayout()));
525
526 Type *RetTy = (Type *)StructType::get(Ty, Ty);
527
528 SDLoc dl(Op);
529 TargetLowering::CallLoweringInfo CLI(DAG);
530 CLI.setDebugLoc(dl)
531 .setChain(InChain)
532 .setLibCallee(DAG.getLibcalls().getLibcallImplCallingConv(LCImpl), RetTy,
533 Callee, std::move(Args))
534 .setInRegister()
535 .setSExtResult(IsSigned)
536 .setZExtResult(!IsSigned);
537
538 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
539 return CallInfo.first;
540}
541
542SDValue AVRTargetLowering::LowerGlobalAddress(SDValue Op,
543 SelectionDAG &DAG) const {
544 auto DL = DAG.getDataLayout();
545
546 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
547 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
548
549 // Create the TargetGlobalAddress node, folding in the constant offset.
551 DAG.getTargetGlobalAddress(GV, SDLoc(Op), getPointerTy(DL), Offset);
552 return DAG.getNode(AVRISD::WRAPPER, SDLoc(Op), getPointerTy(DL), Result);
553}
554
555SDValue AVRTargetLowering::LowerBlockAddress(SDValue Op,
556 SelectionDAG &DAG) const {
557 auto DL = DAG.getDataLayout();
558 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
559
560 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(DL));
561
562 return DAG.getNode(AVRISD::WRAPPER, SDLoc(Op), getPointerTy(DL), Result);
563}
564
565/// IntCCToAVRCC - Convert a DAG integer condition code to an AVR CC.
567 switch (CC) {
568 default:
569 llvm_unreachable("Unknown condition code!");
570 case ISD::SETEQ:
571 return AVRCC::COND_EQ;
572 case ISD::SETNE:
573 return AVRCC::COND_NE;
574 case ISD::SETGE:
575 return AVRCC::COND_GE;
576 case ISD::SETLT:
577 return AVRCC::COND_LT;
578 case ISD::SETUGE:
579 return AVRCC::COND_SH;
580 case ISD::SETULT:
581 return AVRCC::COND_LO;
582 }
583}
584
585/// Returns appropriate CP/CPI/CPC nodes code for the given 8/16-bit operands.
586SDValue AVRTargetLowering::getAVRCmp(SDValue LHS, SDValue RHS,
587 SelectionDAG &DAG, SDLoc DL) const {
588 assert((LHS.getSimpleValueType() == RHS.getSimpleValueType()) &&
589 "LHS and RHS have different types");
590 assert(((LHS.getSimpleValueType() == MVT::i16) ||
591 (LHS.getSimpleValueType() == MVT::i8)) &&
592 "invalid comparison type");
593
594 SDValue Cmp;
595
596 if (LHS.getSimpleValueType() == MVT::i16 && isa<ConstantSDNode>(RHS)) {
597 uint64_t Imm = RHS->getAsZExtVal();
598 // Generate a CPI/CPC pair if RHS is a 16-bit constant. Use the zero
599 // register for the constant RHS if its lower or higher byte is zero.
600 SDValue LHSlo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, LHS,
601 DAG.getIntPtrConstant(0, DL));
602 SDValue LHShi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, LHS,
603 DAG.getIntPtrConstant(1, DL));
604 SDValue RHSlo = (Imm & 0xff) == 0
605 ? DAG.getRegister(Subtarget.getZeroRegister(), MVT::i8)
606 : DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, RHS,
607 DAG.getIntPtrConstant(0, DL));
608 SDValue RHShi = (Imm & 0xff00) == 0
609 ? DAG.getRegister(Subtarget.getZeroRegister(), MVT::i8)
610 : DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, RHS,
611 DAG.getIntPtrConstant(1, DL));
612 Cmp = DAG.getNode(AVRISD::CMP, DL, MVT::Glue, LHSlo, RHSlo);
613 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHShi, RHShi, Cmp);
614 } else if (RHS.getSimpleValueType() == MVT::i16 && isa<ConstantSDNode>(LHS)) {
615 // Generate a CPI/CPC pair if LHS is a 16-bit constant. Use the zero
616 // register for the constant LHS if its lower or higher byte is zero.
617 uint64_t Imm = LHS->getAsZExtVal();
618 SDValue LHSlo = (Imm & 0xff) == 0
619 ? DAG.getRegister(Subtarget.getZeroRegister(), MVT::i8)
620 : DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, LHS,
621 DAG.getIntPtrConstant(0, DL));
622 SDValue LHShi = (Imm & 0xff00) == 0
623 ? DAG.getRegister(Subtarget.getZeroRegister(), MVT::i8)
624 : DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, LHS,
625 DAG.getIntPtrConstant(1, DL));
626 SDValue RHSlo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, RHS,
627 DAG.getIntPtrConstant(0, DL));
628 SDValue RHShi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, RHS,
629 DAG.getIntPtrConstant(1, DL));
630 Cmp = DAG.getNode(AVRISD::CMP, DL, MVT::Glue, LHSlo, RHSlo);
631 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHShi, RHShi, Cmp);
632 } else {
633 // Generate ordinary 16-bit comparison.
634 Cmp = DAG.getNode(AVRISD::CMP, DL, MVT::Glue, LHS, RHS);
635 }
636
637 return Cmp;
638}
639
640/// Returns appropriate AVR CMP/CMPC nodes and corresponding condition code for
641/// the given operands.
642SDValue AVRTargetLowering::getAVRCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
643 SDValue &AVRcc, SelectionDAG &DAG,
644 SDLoc DL) const {
645 SDValue Cmp;
646 EVT VT = LHS.getValueType();
647 bool UseTest = false;
648
649 switch (CC) {
650 default:
651 break;
652 case ISD::SETLE: {
653 // Swap operands and reverse the branching condition.
654 std::swap(LHS, RHS);
655 CC = ISD::SETGE;
656 break;
657 }
658 case ISD::SETGT: {
659 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
660 switch (C->getSExtValue()) {
661 case -1: {
662 // When doing lhs > -1 use a tst instruction on the top part of lhs
663 // and use brpl instead of using a chain of cp/cpc.
664 UseTest = true;
665 AVRcc = DAG.getConstant(AVRCC::COND_PL, DL, MVT::i8);
666 break;
667 }
668 case 0: {
669 // Turn lhs > 0 into 0 < lhs since 0 can be materialized with
670 // __zero_reg__ in lhs.
671 RHS = LHS;
672 LHS = DAG.getConstant(0, DL, VT);
673 CC = ISD::SETLT;
674 break;
675 }
676 default: {
677 if (C->getConstantIntValue()->isMaxValue(true)) {
678 // Applying this optimization requires calculating rhs+1, which we
679 // can't do if that overflows. Swap operands and reverse the
680 // branching condition instead.
681 std::swap(LHS, RHS);
682 CC = ISD::SETLT;
683 break;
684 }
685
686 // Turn lhs < rhs with lhs constant into rhs >= lhs+1, this allows
687 // us to fold the constant into the cmp instruction.
688 RHS = DAG.getSignedConstant(C->getSExtValue() + 1, DL, VT);
689 CC = ISD::SETGE;
690 break;
691 }
692 }
693 break;
694 }
695 // Swap operands and reverse the branching condition.
696 std::swap(LHS, RHS);
697 CC = ISD::SETLT;
698 break;
699 }
700 case ISD::SETLT: {
701 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
702 switch (C->getSExtValue()) {
703 case 1: {
704 // Turn lhs < 1 into 0 >= lhs since 0 can be materialized with
705 // __zero_reg__ in lhs.
706 RHS = LHS;
707 LHS = DAG.getConstant(0, DL, VT);
708 CC = ISD::SETGE;
709 break;
710 }
711 case 0: {
712 // When doing lhs < 0 use a tst instruction on the top part of lhs
713 // and use brmi instead of using a chain of cp/cpc.
714 UseTest = true;
715 AVRcc = DAG.getConstant(AVRCC::COND_MI, DL, MVT::i8);
716 break;
717 }
718 }
719 }
720 break;
721 }
722 case ISD::SETULE: {
723 // Swap operands and reverse the branching condition.
724 std::swap(LHS, RHS);
725 CC = ISD::SETUGE;
726 break;
727 }
728 case ISD::SETUGT: {
729 // Turn `lhs > rhs` with constant rhs into `lhs >= rhs + 1`, because this
730 // allows us to fold the constant into the cmp instruction.
731 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
732 if (C->getConstantIntValue()->isMaxValue(false)) {
733 // Applying this optimization requires calculating rhs+1, which we can't
734 // do if that overflows; it can happen during i128->i64 lowering.
735 } else {
736 RHS = DAG.getConstant(C->getZExtValue() + 1, DL, VT);
737 CC = ISD::SETUGE;
738 break;
739 }
740 }
741 // Swap operands and reverse the branching condition.
742 std::swap(LHS, RHS);
743 CC = ISD::SETULT;
744 break;
745 }
746 }
747
748 // Expand 32 and 64 bit comparisons with custom CMP and CMPC nodes instead of
749 // using the default and/or/xor expansion code which is much longer.
750 if (VT == MVT::i32) {
751 SDValue LHSlo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS,
752 DAG.getIntPtrConstant(0, DL));
753 SDValue LHShi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS,
754 DAG.getIntPtrConstant(1, DL));
755 SDValue RHSlo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS,
756 DAG.getIntPtrConstant(0, DL));
757 SDValue RHShi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS,
758 DAG.getIntPtrConstant(1, DL));
759
760 if (UseTest) {
761 // When using tst we only care about the highest part.
762 SDValue Top = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, LHShi,
763 DAG.getIntPtrConstant(1, DL));
764 Cmp = DAG.getNode(AVRISD::TST, DL, MVT::Glue, Top);
765 } else {
766 Cmp = getAVRCmp(LHSlo, RHSlo, DAG, DL);
767 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHShi, RHShi, Cmp);
768 }
769 } else if (VT == MVT::i64) {
770 SDValue LHS_0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, LHS,
771 DAG.getIntPtrConstant(0, DL));
772 SDValue LHS_1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, LHS,
773 DAG.getIntPtrConstant(1, DL));
774
775 SDValue LHS0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS_0,
776 DAG.getIntPtrConstant(0, DL));
777 SDValue LHS1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS_0,
778 DAG.getIntPtrConstant(1, DL));
779 SDValue LHS2 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS_1,
780 DAG.getIntPtrConstant(0, DL));
781 SDValue LHS3 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS_1,
782 DAG.getIntPtrConstant(1, DL));
783
784 SDValue RHS_0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, RHS,
785 DAG.getIntPtrConstant(0, DL));
786 SDValue RHS_1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, RHS,
787 DAG.getIntPtrConstant(1, DL));
788
789 SDValue RHS0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS_0,
790 DAG.getIntPtrConstant(0, DL));
791 SDValue RHS1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS_0,
792 DAG.getIntPtrConstant(1, DL));
793 SDValue RHS2 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS_1,
794 DAG.getIntPtrConstant(0, DL));
795 SDValue RHS3 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS_1,
796 DAG.getIntPtrConstant(1, DL));
797
798 if (UseTest) {
799 // When using tst we only care about the highest part.
800 SDValue Top = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, LHS3,
801 DAG.getIntPtrConstant(1, DL));
802 Cmp = DAG.getNode(AVRISD::TST, DL, MVT::Glue, Top);
803 } else {
804 Cmp = getAVRCmp(LHS0, RHS0, DAG, DL);
805 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHS1, RHS1, Cmp);
806 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHS2, RHS2, Cmp);
807 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHS3, RHS3, Cmp);
808 }
809 } else if (VT == MVT::i8 || VT == MVT::i16) {
810 if (UseTest) {
811 // When using tst we only care about the highest part.
812 Cmp = DAG.getNode(AVRISD::TST, DL, MVT::Glue,
813 (VT == MVT::i8)
814 ? LHS
815 : DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8,
816 LHS, DAG.getIntPtrConstant(1, DL)));
817 } else {
818 Cmp = getAVRCmp(LHS, RHS, DAG, DL);
819 }
820 } else {
821 llvm_unreachable("Invalid comparison size");
822 }
823
824 // When using a test instruction AVRcc is already set.
825 if (!UseTest) {
826 AVRcc = DAG.getConstant(intCCToAVRCC(CC), DL, MVT::i8);
827 }
828
829 return Cmp;
830}
831
832SDValue AVRTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
833 SDValue Chain = Op.getOperand(0);
834 ISD::CondCode CC = Op.getOperandCondCode(1);
835 SDValue LHS = Op.getOperand(2);
836 SDValue RHS = Op.getOperand(3);
837 SDValue Dest = Op.getOperand(4);
838 SDLoc dl(Op);
839
840 SDValue TargetCC;
841 SDValue Cmp = getAVRCmp(LHS, RHS, CC, TargetCC, DAG, dl);
842
843 return DAG.getNode(AVRISD::BRCOND, dl, MVT::Other, Chain, Dest, TargetCC,
844 Cmp);
845}
846
847SDValue AVRTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
848 SDValue LHS = Op.getOperand(0);
849 SDValue RHS = Op.getOperand(1);
850 SDValue TrueV = Op.getOperand(2);
851 SDValue FalseV = Op.getOperand(3);
852 ISD::CondCode CC = Op.getOperandCondCode(4);
853 SDLoc dl(Op);
854
855 SDValue TargetCC;
856 SDValue Cmp = getAVRCmp(LHS, RHS, CC, TargetCC, DAG, dl);
857
858 SDValue Ops[] = {TrueV, FalseV, TargetCC, Cmp};
859
860 return DAG.getNode(AVRISD::SELECT_CC, dl, Op.getValueType(), Ops);
861}
862
863SDValue AVRTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
864 SDValue LHS = Op.getOperand(0);
865 SDValue RHS = Op.getOperand(1);
866 ISD::CondCode CC = Op.getOperandCondCode(2);
867 SDLoc DL(Op);
868
869 SDValue TargetCC;
870 SDValue Cmp = getAVRCmp(LHS, RHS, CC, TargetCC, DAG, DL);
871
872 SDValue TrueV = DAG.getConstant(1, DL, Op.getValueType());
873 SDValue FalseV = DAG.getConstant(0, DL, Op.getValueType());
874 SDValue Ops[] = {TrueV, FalseV, TargetCC, Cmp};
875
876 return DAG.getNode(AVRISD::SELECT_CC, DL, Op.getValueType(), Ops);
877}
878
879SDValue AVRTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
880 const MachineFunction &MF = DAG.getMachineFunction();
881 const AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>();
882 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
883 auto DL = DAG.getDataLayout();
884 SDLoc dl(Op);
885
886 // Vastart just stores the address of the VarArgsFrameIndex slot into the
887 // memory location argument.
888 SDValue FI = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(), getPointerTy(DL));
889
890 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
891 MachinePointerInfo(SV));
892}
893
894// Modify the existing ISD::INLINEASM node to add the implicit zero register.
895SDValue AVRTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const {
896 SDValue ZeroReg = DAG.getRegister(Subtarget.getZeroRegister(), MVT::i8);
897 if (Op.getOperand(Op.getNumOperands() - 1) == ZeroReg ||
898 Op.getOperand(Op.getNumOperands() - 2) == ZeroReg) {
899 // Zero register has already been added. Don't add it again.
900 // If this isn't handled, we get called over and over again.
901 return Op;
902 }
903
904 // Get a list of operands to the new INLINEASM node. This is mostly a copy,
905 // with some edits.
906 // Add the following operands at the end (but before the glue node, if it's
907 // there):
908 // - The flags of the implicit zero register operand.
909 // - The implicit zero register operand itself.
910 SDLoc dl(Op);
912 SDNode *N = Op.getNode();
913 SDValue Glue;
914 for (unsigned I = 0; I < N->getNumOperands(); I++) {
915 SDValue Operand = N->getOperand(I);
916 if (Operand.getValueType() == MVT::Glue) {
917 // The glue operand always needs to be at the end, so we need to treat it
918 // specially.
919 Glue = Operand;
920 } else {
921 Ops.push_back(Operand);
922 }
923 }
924 InlineAsm::Flag Flags(InlineAsm::Kind::RegUse, 1);
925 Ops.push_back(DAG.getTargetConstant(Flags, dl, MVT::i32));
926 Ops.push_back(ZeroReg);
927 if (Glue) {
928 Ops.push_back(Glue);
929 }
930
931 // Replace the current INLINEASM node with a new one that has the zero
932 // register as implicit parameter.
933 SDValue New = DAG.getNode(N->getOpcode(), dl, N->getVTList(), Ops);
934 DAG.ReplaceAllUsesOfValueWith(Op, New);
935 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), New.getValue(1));
936
937 return New;
938}
939
941 switch (Op.getOpcode()) {
942 default:
943 llvm_unreachable("Don't know how to custom lower this!");
944 case ISD::SHL:
945 case ISD::SRA:
946 case ISD::SRL:
947 case ISD::ROTL:
948 case ISD::ROTR:
949 return LowerShifts(Op, DAG);
951 return LowerGlobalAddress(Op, DAG);
953 return LowerBlockAddress(Op, DAG);
954 case ISD::BR_CC:
955 return LowerBR_CC(Op, DAG);
956 case ISD::SELECT_CC:
957 return LowerSELECT_CC(Op, DAG);
958 case ISD::SETCC:
959 return LowerSETCC(Op, DAG);
960 case ISD::VASTART:
961 return LowerVASTART(Op, DAG);
962 case ISD::SDIVREM:
963 case ISD::UDIVREM:
964 return LowerDivRem(Op, DAG);
965 case ISD::INLINEASM:
966 return LowerINLINEASM(Op, DAG);
967 case ISD::FRAMEADDR:
968 return LowerFRAMEADDR(Op, DAG);
969 case ISD::RETURNADDR:
970 return LowerRETURNADDR(Op, DAG);
971 }
972
973 return SDValue();
974}
975
976SDValue AVRTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
977 // The frame pointer (Y = r29:r28) is set up to contain the stack pointer
978 // *after* the frame has been allocated, i.e. Y == SP_entry - StackSize,
979 // which means it points to the lowest address of the frame: it is really a
980 // frame *base* rather than the canonical frame address. The slot holding the
981 // caller's Y therefore sits at a function dependent offset (the frame size)
982 // above it. Walking the frame chain is only possible for the current frame.
983 //
984 // This is also what avr-gcc returns for __builtin_frame_address(0).
985 if (Op.getConstantOperandVal(0) > 0)
986 // Use the legalizer's default expansion, which is to return 0 (what this
987 // function is documented to do).
988 return SDValue();
989
991 // Mark frame address as taken, so that during frame lowering we're forced to
992 // emit frame pointer register (R29R28) we rely on here.
993 MFI.setFrameAddressIsTaken(true);
994
995 // Return the frame pointer register (R29R28).
996 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
997 Register FP = TRI->getFrameRegister(DAG.getMachineFunction());
998 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), FP,
999 Op.getValueType());
1000}
1001
1002SDValue AVRTargetLowering::LowerRETURNADDR(SDValue Op,
1003 SelectionDAG &DAG) const {
1004 // AVR has no link register: the return address is pushed onto the stack by
1005 // the call instruction. The stack pointer always points at the first free
1006 // byte, so the pushed return address ends up right below the local area (the
1007 // incoming stack arguments), which starts at SP_entry + 3, or SP_entry + 4
1008 // with a 22-bit PC.
1009 //
1010 // The return address is pushed most significant byte first, hence it is
1011 // stored big-endian: [SP_entry + 1] is the high byte and [SP_entry + 2] the
1012 // low byte. This is why avr-gcc has to swap the two bytes it reads for
1013 // __builtin_return_address(0).
1014 //
1015 // Walking the frame chain is not possible, because the distance between the
1016 // frame base and the slot holding the caller's return address depends on the
1017 // caller's frame size, which is not known here. This is also what avr-gcc
1018 // does for __builtin_return_address(1), which returns zero.
1019 if (Op.getConstantOperandVal(0) > 0)
1020 // Use the legalizer's default expansion, which is to return 0 (what this
1021 // function is documented to do).
1022 return SDValue();
1023
1024 MachineFunction &MF = DAG.getMachineFunction();
1025 MachineFrameInfo &MFI = MF.getFrameInfo();
1026 // Mark return address as taken, so that during frame lowering we're forced to
1027 // emit frame pointer register (R29R28) we rely on here.
1028 MFI.setReturnAddressIsTaken(true);
1029
1030 SDLoc DL(Op);
1031 EVT PtrVT = getPointerTy(DAG.getDataLayout());
1032
1033 // A call pushes as many bytes as the program counter is wide: three on
1034 // devices with a 22-bit PC (the ones providing EIJMP/EICALL), two elsewhere.
1035 // Only the two low bytes of the return address are returned, so on the former
1036 // they are found one byte higher up.
1037 //
1038 // A fixed object at offset N is located at SP_entry + N + 3, or at
1039 // SP_entry + N + 4 with a 22-bit PC (see AVRFrameLowering), so the two low
1040 // bytes of the return address are the fixed object at offset -2 on both.
1041 // Note that a frame index can only be referenced through Y, so taking the
1042 // return address forces the function to have a frame pointer (see
1043 // AVRFrameLowering::hasFPImpl).
1044 int FI = MFI.CreateFixedObject(2, -2, true);
1045 SDValue Addr = DAG.getFrameIndex(FI, PtrVT);
1046
1047 // Load the two bytes separately and put them in the right halves of the
1048 // result, which is cheaper than loading a word and byte swapping it.
1049 SDValue Hi = DAG.getLoad(MVT::i8, DL, DAG.getEntryNode(), Addr,
1051 SDValue Lo =
1052 DAG.getLoad(MVT::i8, DL, DAG.getEntryNode(),
1053 DAG.getObjectPtrOffset(DL, Addr, TypeSize::getFixed(1)),
1055
1056 SDValue Res = DAG.getTargetInsertSubreg(AVR::sub_lo, DL, MVT::i16,
1057 DAG.getUNDEF(MVT::i16), Lo);
1058 return DAG.getTargetInsertSubreg(AVR::sub_hi, DL, MVT::i16, Res, Hi);
1059}
1060
1061/// Replace a node with an illegal result type
1062/// with a new node built out of custom code.
1065 SelectionDAG &DAG) const {
1066 SDLoc DL(N);
1067
1068 switch (N->getOpcode()) {
1069 case ISD::ADD: {
1070 // Convert add (x, imm) into sub (x, -imm).
1071 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
1072 SDValue Sub = DAG.getNode(
1073 ISD::SUB, DL, N->getValueType(0), N->getOperand(0),
1074 DAG.getConstant(-C->getAPIntValue(), DL, C->getValueType(0)));
1075 Results.push_back(Sub);
1076 }
1077 break;
1078 }
1079 default: {
1080 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1081
1082 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1083 Results.push_back(Res.getValue(I));
1084
1085 break;
1086 }
1087 }
1088}
1089
1090/// Return true if the addressing mode represented
1091/// by AM is legal for this target, for a load/store of the specified type.
1093 const AddrMode &AM, Type *Ty,
1094 unsigned AS,
1095 Instruction *I) const {
1096 int64_t Offs = AM.BaseOffs;
1097
1098 // Allow absolute addresses.
1099 if (AM.BaseGV && !AM.HasBaseReg && AM.Scale == 0 && Offs == 0) {
1100 return true;
1101 }
1102
1103 // Flash memory instructions only allow zero offsets.
1104 if (isa<PointerType>(Ty) && AS == AVR::ProgramMemory) {
1105 return false;
1106 }
1107
1108 // Allow reg+<6bit> offset.
1109 if (Offs < 0)
1110 Offs = -Offs;
1111 if (AM.BaseGV == nullptr && AM.HasBaseReg && AM.Scale == 0 &&
1112 isUInt<6>(Offs)) {
1113 return true;
1114 }
1115
1116 return false;
1117}
1118
1119/// Returns true by value, base pointer and
1120/// offset pointer and addressing mode by reference if the node's address
1121/// can be legally represented as pre-indexed load / store address.
1123 SDValue &Offset,
1125 SelectionDAG &DAG) const {
1126 EVT VT;
1127 const SDNode *Op;
1128 SDLoc DL(N);
1129
1130 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1131 VT = LD->getMemoryVT();
1132 Op = LD->getBasePtr().getNode();
1133 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
1134 return false;
1136 return false;
1137 }
1138 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1139 VT = ST->getMemoryVT();
1140 Op = ST->getBasePtr().getNode();
1142 return false;
1143 }
1144 } else {
1145 return false;
1146 }
1147
1148 if (VT != MVT::i8 && VT != MVT::i16) {
1149 return false;
1150 }
1151
1152 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) {
1153 return false;
1154 }
1155
1156 if (const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
1157 int RHSC = RHS->getSExtValue();
1158 if (Op->getOpcode() == ISD::SUB)
1159 RHSC = -RHSC;
1160
1161 if ((VT == MVT::i16 && RHSC != -2) || (VT == MVT::i8 && RHSC != -1)) {
1162 return false;
1163 }
1164
1165 Base = Op->getOperand(0);
1166 Offset = DAG.getSignedConstant(RHSC, DL, MVT::i8);
1167 AM = ISD::PRE_DEC;
1168
1169 return true;
1170 }
1171
1172 return false;
1173}
1174
1175/// Returns true by value, base pointer and
1176/// offset pointer and addressing mode by reference if this node can be
1177/// combined with a load / store to form a post-indexed load / store.
1179 SDValue &Base,
1180 SDValue &Offset,
1182 SelectionDAG &DAG) const {
1183 EVT VT;
1184 SDValue Ptr;
1185 SDLoc DL(N);
1186
1187 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1188 VT = LD->getMemoryVT();
1189 Ptr = LD->getBasePtr();
1190 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
1191 return false;
1192 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1193 VT = ST->getMemoryVT();
1194 Ptr = ST->getBasePtr();
1195 // We can not store to program memory.
1197 return false;
1198 // Since the high byte need to be stored first, we can not emit
1199 // i16 post increment store like:
1200 // st X+, r24
1201 // st X+, r25
1202 if (VT == MVT::i16 && !Subtarget.hasLowByteFirst())
1203 return false;
1204 } else {
1205 return false;
1206 }
1207
1208 if (VT != MVT::i8 && VT != MVT::i16) {
1209 return false;
1210 }
1211
1212 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) {
1213 return false;
1214 }
1215
1216 if (const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
1217 int RHSC = RHS->getSExtValue();
1218 if (Op->getOpcode() == ISD::SUB)
1219 RHSC = -RHSC;
1220 if ((VT == MVT::i16 && RHSC != 2) || (VT == MVT::i8 && RHSC != 1)) {
1221 return false;
1222 }
1223
1224 // FIXME: We temporarily disable post increment load from program memory,
1225 // due to bug https://github.com/llvm/llvm-project/issues/59914.
1226 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
1228 return false;
1229
1230 Base = Op->getOperand(0);
1231
1232 // Post-indexing updates the base, so it's not a valid transform
1233 // if that's not the same as the load's pointer.
1234 if (Ptr != Base)
1235 return false;
1236
1237 Offset = DAG.getConstant(RHSC, DL, MVT::i8);
1238 AM = ISD::POST_INC;
1239
1240 return true;
1241 }
1242
1243 return false;
1244}
1245
1247 const GlobalAddressSDNode *GA) const {
1248 return true;
1249}
1250
1251//===----------------------------------------------------------------------===//
1252// Formal Arguments Calling Convention Implementation
1253//===----------------------------------------------------------------------===//
1254
1255#define GET_CALLING_CONV_IMPL
1256#include "AVRGenCallingConv.inc"
1257
1258/// Registers for calling conventions, ordered in reverse as required by ABI.
1259/// Both arrays must be of the same length.
1260static const MCPhysReg RegList8AVR[] = {
1261 AVR::R25, AVR::R24, AVR::R23, AVR::R22, AVR::R21, AVR::R20,
1262 AVR::R19, AVR::R18, AVR::R17, AVR::R16, AVR::R15, AVR::R14,
1263 AVR::R13, AVR::R12, AVR::R11, AVR::R10, AVR::R9, AVR::R8};
1264static const MCPhysReg RegList8Tiny[] = {AVR::R25, AVR::R24, AVR::R23,
1265 AVR::R22, AVR::R21, AVR::R20};
1266static const MCPhysReg RegList16AVR[] = {
1267 AVR::R26R25, AVR::R25R24, AVR::R24R23, AVR::R23R22, AVR::R22R21,
1268 AVR::R21R20, AVR::R20R19, AVR::R19R18, AVR::R18R17, AVR::R17R16,
1269 AVR::R16R15, AVR::R15R14, AVR::R14R13, AVR::R13R12, AVR::R12R11,
1270 AVR::R11R10, AVR::R10R9, AVR::R9R8};
1271static const MCPhysReg RegList16Tiny[] = {AVR::R26R25, AVR::R25R24,
1272 AVR::R24R23, AVR::R23R22,
1273 AVR::R22R21, AVR::R21R20};
1274
1275static_assert(std::size(RegList8AVR) == std::size(RegList16AVR),
1276 "8-bit and 16-bit register arrays must be of equal length");
1277static_assert(std::size(RegList8Tiny) == std::size(RegList16Tiny),
1278 "8-bit and 16-bit register arrays must be of equal length");
1279
1280/// Analyze incoming and outgoing function arguments. We need custom C++ code
1281/// to handle special constraints in the ABI.
1282/// In addition, all pieces of a certain argument have to be passed either
1283/// using registers or the stack but never mixing both.
1284template <typename ArgT>
1286 const Function *F, const DataLayout *TD,
1287 const SmallVectorImpl<ArgT> &Args,
1289 CCState &CCInfo, bool Tiny) {
1290 // Choose the proper register list for argument passing according to the ABI.
1291 ArrayRef<MCPhysReg> RegList8;
1292 ArrayRef<MCPhysReg> RegList16;
1293 if (Tiny) {
1294 RegList8 = ArrayRef(RegList8Tiny);
1295 RegList16 = ArrayRef(RegList16Tiny);
1296 } else {
1297 RegList8 = ArrayRef(RegList8AVR);
1298 RegList16 = ArrayRef(RegList16AVR);
1299 }
1300
1301 unsigned NumArgs = Args.size();
1302 // This is the index of the last used register, in RegList*.
1303 // -1 means R26 (R26 is never actually used in CC).
1304 int RegLastIdx = -1;
1305 // Once a value is passed to the stack it will always be used
1306 bool UseStack = false;
1307 for (unsigned i = 0; i != NumArgs;) {
1308 MVT VT = Args[i].VT;
1309 // We have to count the number of bytes for each function argument, that is
1310 // those Args with the same OrigArgIndex. This is important in case the
1311 // function takes an aggregate type.
1312 // Current argument will be between [i..j).
1313 unsigned ArgIndex = Args[i].OrigArgIndex;
1314 unsigned TotalBytes = VT.getStoreSize();
1315 unsigned j = i + 1;
1316 for (; j != NumArgs; ++j) {
1317 if (Args[j].OrigArgIndex != ArgIndex)
1318 break;
1319 TotalBytes += Args[j].VT.getStoreSize();
1320 }
1321 // Round up to even number of bytes.
1322 TotalBytes = alignTo(TotalBytes, 2);
1323 // Skip zero sized arguments
1324 if (TotalBytes == 0)
1325 continue;
1326 // The index of the first register to be used
1327 unsigned RegIdx = RegLastIdx + TotalBytes;
1328 RegLastIdx = RegIdx;
1329 // If there are not enough registers, use the stack
1330 if (RegIdx >= RegList8.size()) {
1331 UseStack = true;
1332 }
1333 for (; i != j; ++i) {
1334 MVT VT = Args[i].VT;
1335
1336 if (UseStack) {
1337 auto evt = EVT(VT).getTypeForEVT(CCInfo.getContext());
1338 unsigned Offset = CCInfo.AllocateStack(TD->getTypeAllocSize(evt),
1339 TD->getABITypeAlign(evt));
1340 CCInfo.addLoc(
1342 } else {
1343 unsigned Reg;
1344 if (VT == MVT::i8) {
1345 Reg = CCInfo.AllocateReg(RegList8[RegIdx]);
1346 } else if (VT == MVT::i16) {
1347 Reg = CCInfo.AllocateReg(RegList16[RegIdx]);
1348 } else {
1350 "calling convention can only manage i8 and i16 types");
1351 }
1352 assert(Reg && "register not available in calling convention");
1353 CCInfo.addLoc(CCValAssign::getReg(i, VT, Reg, VT, CCValAssign::Full));
1354 // Registers inside a particular argument are sorted in increasing order
1355 // (remember the array is reversed).
1356 RegIdx -= VT.getStoreSize();
1357 }
1358 }
1359 }
1360}
1361
1362/// Count the total number of bytes needed to pass or return these arguments.
1363template <typename ArgT>
1364static unsigned
1366 unsigned TotalBytes = 0;
1367
1368 for (const ArgT &Arg : Args) {
1369 TotalBytes += Arg.VT.getStoreSize();
1370 }
1371 return TotalBytes;
1372}
1373
1374/// Analyze incoming and outgoing value of returning from a function.
1375/// The algorithm is similar to analyzeArguments, but there can only be
1376/// one value, possibly an aggregate, and it is limited to 8 bytes.
1377template <typename ArgT>
1379 CCState &CCInfo, bool Tiny) {
1380 unsigned NumArgs = Args.size();
1381 unsigned TotalBytes = getTotalArgumentsSizeInBytes(Args);
1382 // CanLowerReturn() guarantees this assertion.
1383 if (Tiny)
1384 assert(TotalBytes <= 4 &&
1385 "return values greater than 4 bytes cannot be lowered on AVRTiny");
1386 else
1387 assert(TotalBytes <= 8 &&
1388 "return values greater than 8 bytes cannot be lowered on AVR");
1389
1390 // Choose the proper register list for argument passing according to the ABI.
1391 ArrayRef<MCPhysReg> RegList8;
1392 ArrayRef<MCPhysReg> RegList16;
1393 if (Tiny) {
1394 RegList8 = ArrayRef(RegList8Tiny);
1395 RegList16 = ArrayRef(RegList16Tiny);
1396 } else {
1397 RegList8 = ArrayRef(RegList8AVR);
1398 RegList16 = ArrayRef(RegList16AVR);
1399 }
1400
1401 // GCC-ABI says that the size is rounded up to the next even number,
1402 // but actually once it is more than 4 it will always round up to 8.
1403 if (TotalBytes > 4) {
1404 TotalBytes = 8;
1405 } else {
1406 TotalBytes = alignTo(TotalBytes, 2);
1407 }
1408
1409 // The index of the first register to use.
1410 int RegIdx = TotalBytes - 1;
1411 for (unsigned i = 0; i != NumArgs; ++i) {
1412 MVT VT = Args[i].VT;
1413 unsigned Reg;
1414 if (VT == MVT::i8) {
1415 Reg = CCInfo.AllocateReg(RegList8[RegIdx]);
1416 } else if (VT == MVT::i16) {
1417 Reg = CCInfo.AllocateReg(RegList16[RegIdx]);
1418 } else {
1419 llvm_unreachable("calling convention can only manage i8 and i16 types");
1420 }
1421 assert(Reg && "register not available in calling convention");
1422 CCInfo.addLoc(CCValAssign::getReg(i, VT, Reg, VT, CCValAssign::Full));
1423 // Registers sort in increasing order
1424 RegIdx -= VT.getStoreSize();
1425 }
1426}
1427
1428SDValue AVRTargetLowering::LowerFormalArguments(
1429 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1430 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1431 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1432 MachineFunction &MF = DAG.getMachineFunction();
1433 MachineFrameInfo &MFI = MF.getFrameInfo();
1434 auto DL = DAG.getDataLayout();
1435
1436 // Assign locations to all of the incoming arguments.
1438 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1439 *DAG.getContext());
1440
1441 // Variadic functions do not need all the analysis below.
1442 if (isVarArg) {
1443 CCInfo.AnalyzeFormalArguments(Ins, ArgCC_AVR_Vararg);
1444 } else {
1445 analyzeArguments(nullptr, &MF.getFunction(), &DL, Ins, ArgLocs, CCInfo,
1446 Subtarget.hasTinyEncoding());
1447 }
1448
1449 SDValue ArgValue;
1450 for (CCValAssign &VA : ArgLocs) {
1451
1452 // Arguments stored on registers.
1453 if (VA.isRegLoc()) {
1454 EVT RegVT = VA.getLocVT();
1455 const TargetRegisterClass *RC;
1456 if (RegVT == MVT::i8) {
1457 RC = &AVR::GPR8RegClass;
1458 } else if (RegVT == MVT::i16) {
1459 RC = &AVR::DREGSRegClass;
1460 } else {
1461 llvm_unreachable("Unknown argument type!");
1462 }
1463
1464 Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
1465 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1466
1467 // :NOTE: Clang should not promote any i8 into i16 but for safety the
1468 // following code will handle zexts or sexts generated by other
1469 // front ends. Otherwise:
1470 // If this is an 8 bit value, it is really passed promoted
1471 // to 16 bits. Insert an assert[sz]ext to capture this, then
1472 // truncate to the right size.
1473 switch (VA.getLocInfo()) {
1474 default:
1475 llvm_unreachable("Unknown loc info!");
1476 case CCValAssign::Full:
1477 break;
1478 case CCValAssign::BCvt:
1479 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1480 break;
1481 case CCValAssign::SExt:
1482 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1483 DAG.getValueType(VA.getValVT()));
1484 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1485 break;
1486 case CCValAssign::ZExt:
1487 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1488 DAG.getValueType(VA.getValVT()));
1489 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1490 break;
1491 }
1492
1493 InVals.push_back(ArgValue);
1494 } else {
1495 // Only arguments passed on the stack should make it here.
1496 assert(VA.isMemLoc());
1497
1498 EVT LocVT = VA.getLocVT();
1499
1500 // Create the frame index object for this incoming parameter.
1501 int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
1502 VA.getLocMemOffset(), true);
1503
1504 // Create the SelectionDAG nodes corresponding to a load
1505 // from this parameter.
1506 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DL));
1507 InVals.push_back(DAG.getLoad(LocVT, dl, Chain, FIN,
1509 }
1510 }
1511
1512 // If the function takes variable number of arguments, make a frame index for
1513 // the start of the first vararg value... for expansion of llvm.va_start.
1514 if (isVarArg) {
1515 unsigned StackSize = CCInfo.getStackSize();
1516 AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>();
1517
1518 AFI->setVarArgsFrameIndex(MFI.CreateFixedObject(2, StackSize, true));
1519 }
1520
1521 return Chain;
1522}
1523
1524//===----------------------------------------------------------------------===//
1525// Call Calling Convention Implementation
1526//===----------------------------------------------------------------------===//
1527
1528SDValue AVRTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1529 SmallVectorImpl<SDValue> &InVals) const {
1530 SelectionDAG &DAG = CLI.DAG;
1531 SDLoc &DL = CLI.DL;
1532 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1533 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1534 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1535 SDValue Chain = CLI.Chain;
1536 SDValue Callee = CLI.Callee;
1537 bool &isTailCall = CLI.IsTailCall;
1538 CallingConv::ID CallConv = CLI.CallConv;
1539 bool isVarArg = CLI.IsVarArg;
1540
1541 MachineFunction &MF = DAG.getMachineFunction();
1542
1543 // AVR does not yet support tail call optimization.
1544 isTailCall = false;
1545
1546 // Analyze operands of the call, assigning locations to each operand.
1548 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1549 *DAG.getContext());
1550
1551 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1552 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1553 // node so that legalize doesn't hack it.
1554 const Function *F = nullptr;
1555 if (const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1556 const GlobalValue *GV = G->getGlobal();
1557 if (isa<Function>(GV))
1558 F = cast<Function>(GV);
1559 Callee =
1560 DAG.getTargetGlobalAddress(GV, DL, getPointerTy(DAG.getDataLayout()));
1561 } else if (const ExternalSymbolSDNode *ES =
1563 Callee = DAG.getTargetExternalSymbol(ES->getSymbol(),
1564 getPointerTy(DAG.getDataLayout()));
1565 }
1566
1567 // Variadic functions do not need all the analysis below.
1568 if (isVarArg) {
1569 CCInfo.AnalyzeCallOperands(Outs, ArgCC_AVR_Vararg);
1570 } else {
1571 analyzeArguments(&CLI, F, &DAG.getDataLayout(), Outs, ArgLocs, CCInfo,
1572 Subtarget.hasTinyEncoding());
1573 }
1574
1575 // Get a count of how many bytes are to be pushed on the stack.
1576 unsigned NumBytes = CCInfo.getStackSize();
1577
1578 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
1579
1581
1582 // First, walk the register assignments, inserting copies.
1583 unsigned AI, AE;
1584 bool HasStackArgs = false;
1585 for (AI = 0, AE = ArgLocs.size(); AI != AE; ++AI) {
1586 CCValAssign &VA = ArgLocs[AI];
1587 EVT RegVT = VA.getLocVT();
1588 SDValue Arg = OutVals[AI];
1589
1590 // Promote the value if needed. With Clang this should not happen.
1591 switch (VA.getLocInfo()) {
1592 default:
1593 llvm_unreachable("Unknown loc info!");
1594 case CCValAssign::Full:
1595 break;
1596 case CCValAssign::SExt:
1597 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, RegVT, Arg);
1598 break;
1599 case CCValAssign::ZExt:
1600 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, RegVT, Arg);
1601 break;
1602 case CCValAssign::AExt:
1603 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, RegVT, Arg);
1604 break;
1605 case CCValAssign::BCvt:
1606 Arg = DAG.getNode(ISD::BITCAST, DL, RegVT, Arg);
1607 break;
1608 }
1609
1610 // Stop when we encounter a stack argument, we need to process them
1611 // in reverse order in the loop below.
1612 if (VA.isMemLoc()) {
1613 HasStackArgs = true;
1614 break;
1615 }
1616
1617 // Arguments that can be passed on registers must be kept in the RegsToPass
1618 // vector.
1619 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1620 }
1621
1622 // Second, stack arguments have to walked.
1623 // Previously this code created chained stores but those chained stores appear
1624 // to be unchained in the legalization phase. Therefore, do not attempt to
1625 // chain them here. In fact, chaining them here somehow causes the first and
1626 // second store to be reversed which is the exact opposite of the intended
1627 // effect.
1628 if (HasStackArgs) {
1629 SmallVector<SDValue, 8> MemOpChains;
1630 for (; AI != AE; AI++) {
1631 CCValAssign &VA = ArgLocs[AI];
1632 SDValue Arg = OutVals[AI];
1633
1634 assert(VA.isMemLoc());
1635
1636 // SP points to one stack slot further so add one to adjust it.
1637 SDValue PtrOff = DAG.getNode(
1638 ISD::ADD, DL, getPointerTy(DAG.getDataLayout()),
1639 DAG.getRegister(AVR::SP, getPointerTy(DAG.getDataLayout())),
1640 DAG.getIntPtrConstant(VA.getLocMemOffset() + 1, DL));
1641
1642 MemOpChains.push_back(
1643 DAG.getStore(Chain, DL, Arg, PtrOff,
1644 MachinePointerInfo::getStack(MF, VA.getLocMemOffset())));
1645 }
1646
1647 if (!MemOpChains.empty())
1648 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1649 }
1650
1651 // Build a sequence of copy-to-reg nodes chained together with token chain and
1652 // flag operands which copy the outgoing args into registers. The InGlue in
1653 // necessary since all emited instructions must be stuck together.
1654 SDValue InGlue;
1655 for (auto Reg : RegsToPass) {
1656 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, InGlue);
1657 InGlue = Chain.getValue(1);
1658 }
1659
1660 // Returns a chain & a flag for retval copy to use.
1661 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1663 Ops.push_back(Chain);
1664 Ops.push_back(Callee);
1665
1666 // Add argument registers to the end of the list so that they are known live
1667 // into the call.
1668 for (auto Reg : RegsToPass) {
1669 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
1670 }
1671
1672 // The zero register (usually R1) must be passed as an implicit register so
1673 // that this register is correctly zeroed in interrupts.
1674 Ops.push_back(DAG.getRegister(Subtarget.getZeroRegister(), MVT::i8));
1675
1676 // Add a register mask operand representing the call-preserved registers.
1677 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1678 const uint32_t *Mask =
1679 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
1680 assert(Mask && "Missing call preserved mask for calling convention");
1681 Ops.push_back(DAG.getRegisterMask(Mask));
1682
1683 if (InGlue.getNode()) {
1684 Ops.push_back(InGlue);
1685 }
1686
1687 Chain = DAG.getNode(AVRISD::CALL, DL, NodeTys, Ops);
1688 InGlue = Chain.getValue(1);
1689
1690 // Create the CALLSEQ_END node.
1691 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, InGlue, DL);
1692
1693 if (!Ins.empty()) {
1694 InGlue = Chain.getValue(1);
1695 }
1696
1697 // Handle result values, copying them out of physregs into vregs that we
1698 // return.
1699 return LowerCallResult(Chain, InGlue, CallConv, isVarArg, Ins, DL, DAG,
1700 InVals);
1701}
1702
1703/// Lower the result values of a call into the
1704/// appropriate copies out of appropriate physical registers.
1705///
1706SDValue AVRTargetLowering::LowerCallResult(
1707 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool isVarArg,
1708 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1709 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1710
1711 // Assign locations to each value returned by this call.
1713 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1714 *DAG.getContext());
1715
1716 // Handle runtime calling convs.
1717 if (CallConv == CallingConv::AVR_BUILTIN) {
1718 CCInfo.AnalyzeCallResult(Ins, RetCC_AVR_BUILTIN);
1719 } else {
1720 analyzeReturnValues(Ins, CCInfo, Subtarget.hasTinyEncoding());
1721 }
1722
1723 // Copy all of the result registers out of their specified physreg.
1724 for (CCValAssign const &RVLoc : RVLocs) {
1725 Chain = DAG.getCopyFromReg(Chain, dl, RVLoc.getLocReg(), RVLoc.getValVT(),
1726 InGlue)
1727 .getValue(1);
1728 InGlue = Chain.getValue(2);
1729 InVals.push_back(Chain.getValue(0));
1730 }
1731
1732 return Chain;
1733}
1734
1735//===----------------------------------------------------------------------===//
1736// Return Value Calling Convention Implementation
1737//===----------------------------------------------------------------------===//
1738
1739bool AVRTargetLowering::CanLowerReturn(
1740 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
1742 const Type *RetTy) const {
1743 if (CallConv == CallingConv::AVR_BUILTIN) {
1745 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1746 return CCInfo.CheckReturn(Outs, RetCC_AVR_BUILTIN);
1747 }
1748
1749 unsigned TotalBytes = getTotalArgumentsSizeInBytes(Outs);
1750 return TotalBytes <= (unsigned)(Subtarget.hasTinyEncoding() ? 4 : 8);
1751}
1752
1753SDValue
1754AVRTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1755 bool isVarArg,
1757 const SmallVectorImpl<SDValue> &OutVals,
1758 const SDLoc &dl, SelectionDAG &DAG) const {
1759 // CCValAssign - represent the assignment of the return value to locations.
1761
1762 // CCState - Info about the registers and stack slot.
1763 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1764 *DAG.getContext());
1765
1766 MachineFunction &MF = DAG.getMachineFunction();
1767
1768 // Analyze return values.
1769 if (CallConv == CallingConv::AVR_BUILTIN) {
1770 CCInfo.AnalyzeReturn(Outs, RetCC_AVR_BUILTIN);
1771 } else {
1772 analyzeReturnValues(Outs, CCInfo, Subtarget.hasTinyEncoding());
1773 }
1774
1775 SDValue Glue;
1776 SmallVector<SDValue, 4> RetOps(1, Chain);
1777 // Copy the result values into the output registers.
1778 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1779 CCValAssign &VA = RVLocs[i];
1780 assert(VA.isRegLoc() && "Can only return in registers!");
1781
1782 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Glue);
1783
1784 // Guarantee that all emitted copies are stuck together with flags.
1785 Glue = Chain.getValue(1);
1786 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1787 }
1788
1789 // Don't emit the ret/reti instruction when the naked attribute is present in
1790 // the function being compiled.
1791 if (MF.getFunction().getAttributes().hasFnAttr(Attribute::Naked)) {
1792 return Chain;
1793 }
1794
1795 const AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>();
1796
1797 if (!AFI->isInterruptOrSignalHandler()) {
1798 // The return instruction has an implicit zero register operand: it must
1799 // contain zero on return.
1800 // This is not needed in interrupts however, where the zero register is
1801 // handled specially (only pushed/popped when needed).
1802 RetOps.push_back(DAG.getRegister(Subtarget.getZeroRegister(), MVT::i8));
1803 }
1804
1805 unsigned RetOpc =
1806 AFI->isInterruptOrSignalHandler() ? AVRISD::RETI_GLUE : AVRISD::RET_GLUE;
1807
1808 RetOps[0] = Chain; // Update chain.
1809
1810 if (Glue.getNode()) {
1811 RetOps.push_back(Glue);
1812 }
1813
1814 return DAG.getNode(RetOpc, dl, MVT::Other, RetOps);
1815}
1816
1817//===----------------------------------------------------------------------===//
1818// Custom Inserters
1819//===----------------------------------------------------------------------===//
1820
1821MachineBasicBlock *AVRTargetLowering::insertShift(MachineInstr &MI,
1823 bool Tiny) const {
1824 unsigned Opc;
1825 const TargetRegisterClass *RC;
1826 bool HasRepeatedOperand = false;
1827 MachineFunction *F = BB->getParent();
1828 MachineRegisterInfo &RI = F->getRegInfo();
1829 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1830 DebugLoc dl = MI.getDebugLoc();
1831
1832 switch (MI.getOpcode()) {
1833 default:
1834 llvm_unreachable("Invalid shift opcode!");
1835 case AVR::Lsl8:
1836 Opc = AVR::ADDRdRr; // LSL is an alias of ADD Rd, Rd
1837 RC = &AVR::GPR8RegClass;
1838 HasRepeatedOperand = true;
1839 break;
1840 case AVR::Lsl16:
1841 Opc = AVR::LSLWRd;
1842 RC = &AVR::DREGSRegClass;
1843 break;
1844 case AVR::Asr8:
1845 Opc = AVR::ASRRd;
1846 RC = &AVR::GPR8RegClass;
1847 break;
1848 case AVR::Asr16:
1849 Opc = AVR::ASRWRd;
1850 RC = &AVR::DREGSRegClass;
1851 break;
1852 case AVR::Lsr8:
1853 Opc = AVR::LSRRd;
1854 RC = &AVR::GPR8RegClass;
1855 break;
1856 case AVR::Lsr16:
1857 Opc = AVR::LSRWRd;
1858 RC = &AVR::DREGSRegClass;
1859 break;
1860 case AVR::Rol8:
1861 Opc = Tiny ? AVR::ROLBRdR17 : AVR::ROLBRdR1;
1862 RC = &AVR::GPR8RegClass;
1863 break;
1864 case AVR::Rol16:
1865 Opc = AVR::ROLWRd;
1866 RC = &AVR::DREGSRegClass;
1867 break;
1868 case AVR::Ror8:
1869 Opc = AVR::RORBRd;
1870 RC = &AVR::GPR8RegClass;
1871 break;
1872 case AVR::Ror16:
1873 Opc = AVR::RORWRd;
1874 RC = &AVR::DREGSRegClass;
1875 break;
1876 }
1877
1878 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1879
1881 for (I = BB->getIterator(); I != F->end() && &(*I) != BB; ++I)
1882 ;
1883 if (I != F->end())
1884 ++I;
1885
1886 // Create loop block.
1887 MachineBasicBlock *LoopBB = F->CreateMachineBasicBlock(LLVM_BB);
1888 MachineBasicBlock *CheckBB = F->CreateMachineBasicBlock(LLVM_BB);
1889 MachineBasicBlock *RemBB = F->CreateMachineBasicBlock(LLVM_BB);
1890
1891 F->insert(I, LoopBB);
1892 F->insert(I, CheckBB);
1893 F->insert(I, RemBB);
1894
1895 // Update machine-CFG edges by transferring all successors of the current
1896 // block to the block containing instructions after shift.
1897 RemBB->splice(RemBB->begin(), BB, std::next(MachineBasicBlock::iterator(MI)),
1898 BB->end());
1899 RemBB->transferSuccessorsAndUpdatePHIs(BB);
1900
1901 // Add edges BB => LoopBB => CheckBB => RemBB, CheckBB => LoopBB.
1902 BB->addSuccessor(CheckBB);
1903 LoopBB->addSuccessor(CheckBB);
1904 CheckBB->addSuccessor(LoopBB);
1905 CheckBB->addSuccessor(RemBB);
1906
1907 Register ShiftAmtReg = RI.createVirtualRegister(&AVR::GPR8RegClass);
1908 Register ShiftAmtReg2 = RI.createVirtualRegister(&AVR::GPR8RegClass);
1909 Register ShiftReg = RI.createVirtualRegister(RC);
1910 Register ShiftReg2 = RI.createVirtualRegister(RC);
1911 Register ShiftAmtSrcReg = MI.getOperand(2).getReg();
1912 Register SrcReg = MI.getOperand(1).getReg();
1913 Register DstReg = MI.getOperand(0).getReg();
1914
1915 // BB:
1916 // rjmp CheckBB
1917 BuildMI(BB, dl, TII.get(AVR::RJMPk)).addMBB(CheckBB);
1918
1919 // LoopBB:
1920 // ShiftReg2 = shift ShiftReg
1921 auto ShiftMI = BuildMI(LoopBB, dl, TII.get(Opc), ShiftReg2).addReg(ShiftReg);
1922 if (HasRepeatedOperand)
1923 ShiftMI.addReg(ShiftReg);
1924
1925 // CheckBB:
1926 // ShiftReg = phi [%SrcReg, BB], [%ShiftReg2, LoopBB]
1927 // ShiftAmt = phi [%N, BB], [%ShiftAmt2, LoopBB]
1928 // DestReg = phi [%SrcReg, BB], [%ShiftReg, LoopBB]
1929 // ShiftAmt2 = ShiftAmt - 1;
1930 // if (ShiftAmt2 >= 0) goto LoopBB;
1931 BuildMI(CheckBB, dl, TII.get(AVR::PHI), ShiftReg)
1932 .addReg(SrcReg)
1933 .addMBB(BB)
1934 .addReg(ShiftReg2)
1935 .addMBB(LoopBB);
1936 BuildMI(CheckBB, dl, TII.get(AVR::PHI), ShiftAmtReg)
1937 .addReg(ShiftAmtSrcReg)
1938 .addMBB(BB)
1939 .addReg(ShiftAmtReg2)
1940 .addMBB(LoopBB);
1941 BuildMI(CheckBB, dl, TII.get(AVR::PHI), DstReg)
1942 .addReg(SrcReg)
1943 .addMBB(BB)
1944 .addReg(ShiftReg2)
1945 .addMBB(LoopBB);
1946
1947 BuildMI(CheckBB, dl, TII.get(AVR::DECRd), ShiftAmtReg2).addReg(ShiftAmtReg);
1948 BuildMI(CheckBB, dl, TII.get(AVR::BRPLk)).addMBB(LoopBB);
1949
1950 MI.eraseFromParent(); // The pseudo instruction is gone now.
1951 return RemBB;
1952}
1953
1954// Do a multibyte AVR shift. Insert shift instructions and put the output
1955// registers in the Regs array.
1956// Because AVR does not have a normal shift instruction (only a single bit shift
1957// instruction), we have to emulate this behavior with other instructions.
1958// It first tries large steps (moving registers around) and then smaller steps
1959// like single bit shifts.
1960// Large shifts actually reduce the number of shifted registers, so the below
1961// algorithms have to work independently of the number of registers that are
1962// shifted.
1963// For more information and background, see this blogpost:
1964// https://aykevl.nl/2021/02/avr-bitshift
1966 MutableArrayRef<std::pair<Register, int>> Regs,
1967 ISD::NodeType Opc, int64_t ShiftAmt) {
1969 const AVRSubtarget &STI = BB->getParent()->getSubtarget<AVRSubtarget>();
1971 const DebugLoc &dl = MI.getDebugLoc();
1972
1973 const bool ShiftLeft = Opc == ISD::SHL;
1974 const bool ArithmeticShift = Opc == ISD::SRA;
1975
1976 // Zero a register, for use in later operations.
1977 Register ZeroReg = MRI.createVirtualRegister(&AVR::GPR8RegClass);
1978 BuildMI(*BB, MI, dl, TII.get(AVR::COPY), ZeroReg)
1979 .addReg(STI.getZeroRegister());
1980
1981 // Do a shift modulo 6 or 7. This is a bit more complicated than most shifts
1982 // and is hard to compose with the rest, so these are special cased.
1983 // The basic idea is to shift one or two bits in the opposite direction and
1984 // then move registers around to get the correct end result.
1985 if (ShiftLeft && (ShiftAmt % 8) >= 6) {
1986 // Left shift modulo 6 or 7.
1987
1988 // Create a slice of the registers we're going to modify, to ease working
1989 // with them.
1990 size_t ShiftRegsOffset = ShiftAmt / 8;
1991 size_t ShiftRegsSize = Regs.size() - ShiftRegsOffset;
1993 Regs.slice(ShiftRegsOffset, ShiftRegsSize);
1994
1995 // Shift one to the right, keeping the least significant bit as the carry
1996 // bit.
1997 insertMultibyteShift(MI, BB, ShiftRegs, ISD::SRL, 1);
1998
1999 // Rotate the least significant bit from the carry bit into a new register
2000 // (that starts out zero).
2001 Register LowByte = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2002 BuildMI(*BB, MI, dl, TII.get(AVR::RORRd), LowByte).addReg(ZeroReg);
2003
2004 // Shift one more to the right if this is a modulo-6 shift.
2005 if (ShiftAmt % 8 == 6) {
2006 insertMultibyteShift(MI, BB, ShiftRegs, ISD::SRL, 1);
2007 Register NewLowByte = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2008 BuildMI(*BB, MI, dl, TII.get(AVR::RORRd), NewLowByte).addReg(LowByte);
2009 LowByte = NewLowByte;
2010 }
2011
2012 // Move all registers to the left, zeroing the bottom registers as needed.
2013 for (size_t I = 0; I < Regs.size(); I++) {
2014 int ShiftRegsIdx = I + 1;
2015 if (ShiftRegsIdx < (int)ShiftRegs.size()) {
2016 Regs[I] = ShiftRegs[ShiftRegsIdx];
2017 } else if (ShiftRegsIdx == (int)ShiftRegs.size()) {
2018 Regs[I] = std::pair(LowByte, 0);
2019 } else {
2020 Regs[I] = std::pair(ZeroReg, 0);
2021 }
2022 }
2023
2024 return;
2025 }
2026
2027 // Right shift modulo 6 or 7.
2028 if (!ShiftLeft && (ShiftAmt % 8) >= 6) {
2029 // Create a view on the registers we're going to modify, to ease working
2030 // with them.
2031 size_t ShiftRegsSize = Regs.size() - (ShiftAmt / 8);
2033 Regs.slice(0, ShiftRegsSize);
2034
2035 // Shift one to the left.
2036 insertMultibyteShift(MI, BB, ShiftRegs, ISD::SHL, 1);
2037
2038 // Sign or zero extend the most significant register into a new register.
2039 // The HighByte is the byte that still has one (or two) bits from the
2040 // original value. The ExtByte is purely a zero/sign extend byte (all bits
2041 // are either 0 or 1).
2042 Register HighByte = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2043 Register ExtByte = 0;
2044 if (ArithmeticShift) {
2045 // Sign-extend bit that was shifted out last.
2046 BuildMI(*BB, MI, dl, TII.get(AVR::SBCRdRr), HighByte)
2047 .addReg(HighByte, RegState::Undef)
2048 .addReg(HighByte, RegState::Undef);
2049 ExtByte = HighByte;
2050 // The highest bit of the original value is the same as the zero-extend
2051 // byte, so HighByte and ExtByte are the same.
2052 } else {
2053 // Use the zero register for zero extending.
2054 ExtByte = ZeroReg;
2055 // Rotate most significant bit into a new register (that starts out zero).
2056 BuildMI(*BB, MI, dl, TII.get(AVR::ADCRdRr), HighByte)
2057 .addReg(ExtByte)
2058 .addReg(ExtByte);
2059 }
2060
2061 // Shift one more to the left for modulo 6 shifts.
2062 if (ShiftAmt % 8 == 6) {
2063 insertMultibyteShift(MI, BB, ShiftRegs, ISD::SHL, 1);
2064 // Shift the topmost bit into the HighByte.
2065 Register NewExt = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2066 BuildMI(*BB, MI, dl, TII.get(AVR::ADCRdRr), NewExt)
2067 .addReg(HighByte)
2068 .addReg(HighByte);
2069 HighByte = NewExt;
2070 }
2071
2072 // Move all to the right, while sign or zero extending.
2073 for (int I = Regs.size() - 1; I >= 0; I--) {
2074 int ShiftRegsIdx = I - (Regs.size() - ShiftRegs.size()) - 1;
2075 if (ShiftRegsIdx >= 0) {
2076 Regs[I] = ShiftRegs[ShiftRegsIdx];
2077 } else if (ShiftRegsIdx == -1) {
2078 Regs[I] = std::pair(HighByte, 0);
2079 } else {
2080 Regs[I] = std::pair(ExtByte, 0);
2081 }
2082 }
2083
2084 return;
2085 }
2086
2087 // For shift amounts of at least one register, simply rename the registers and
2088 // zero the bottom registers.
2089 while (ShiftLeft && ShiftAmt >= 8) {
2090 // Move all registers one to the left.
2091 for (size_t I = 0; I < Regs.size() - 1; I++) {
2092 Regs[I] = Regs[I + 1];
2093 }
2094
2095 // Zero the least significant register.
2096 Regs[Regs.size() - 1] = std::pair(ZeroReg, 0);
2097
2098 // Continue shifts with the leftover registers.
2099 Regs = Regs.drop_back(1);
2100
2101 ShiftAmt -= 8;
2102 }
2103
2104 // And again, the same for right shifts.
2105 Register ShrExtendReg = 0;
2106 if (!ShiftLeft && ShiftAmt >= 8) {
2107 if (ArithmeticShift) {
2108 // Sign extend the most significant register into ShrExtendReg.
2109 ShrExtendReg = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2110 Register Tmp = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2111 BuildMI(*BB, MI, dl, TII.get(AVR::ADDRdRr), Tmp)
2112 .addReg(Regs[0].first, {}, Regs[0].second)
2113 .addReg(Regs[0].first, {}, Regs[0].second);
2114 BuildMI(*BB, MI, dl, TII.get(AVR::SBCRdRr), ShrExtendReg)
2115 .addReg(Tmp)
2116 .addReg(Tmp);
2117 } else {
2118 ShrExtendReg = ZeroReg;
2119 }
2120 for (; ShiftAmt >= 8; ShiftAmt -= 8) {
2121 // Move all registers one to the right.
2122 for (size_t I = Regs.size() - 1; I != 0; I--) {
2123 Regs[I] = Regs[I - 1];
2124 }
2125
2126 // Zero or sign extend the most significant register.
2127 Regs[0] = std::pair(ShrExtendReg, 0);
2128
2129 // Continue shifts with the leftover registers.
2130 Regs = Regs.drop_front(1);
2131 }
2132 }
2133
2134 // The bigger shifts are already handled above.
2135 assert((ShiftAmt < 8) && "Unexpect shift amount");
2136
2137 // Shift by four bits, using a complicated swap/eor/andi/eor sequence.
2138 // It only works for logical shifts because the bits shifted in are all
2139 // zeroes.
2140 // To shift a single byte right, it produces code like this:
2141 // swap r0
2142 // andi r0, 0x0f
2143 // For a two-byte (16-bit) shift, it adds the following instructions to shift
2144 // the upper byte into the lower byte:
2145 // swap r1
2146 // eor r0, r1
2147 // andi r1, 0x0f
2148 // eor r0, r1
2149 // For bigger shifts, it repeats the above sequence. For example, for a 3-byte
2150 // (24-bit) shift it adds:
2151 // swap r2
2152 // eor r1, r2
2153 // andi r2, 0x0f
2154 // eor r1, r2
2155 if (!ArithmeticShift && ShiftAmt >= 4) {
2156 Register Prev = 0;
2157 for (size_t I = 0; I < Regs.size(); I++) {
2158 size_t Idx = ShiftLeft ? I : Regs.size() - I - 1;
2159 Register SwapReg = MRI.createVirtualRegister(&AVR::LD8RegClass);
2160 BuildMI(*BB, MI, dl, TII.get(AVR::SWAPRd), SwapReg)
2161 .addReg(Regs[Idx].first, {}, Regs[Idx].second);
2162 if (I != 0) {
2163 Register R = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2164 BuildMI(*BB, MI, dl, TII.get(AVR::EORRdRr), R)
2165 .addReg(Prev)
2166 .addReg(SwapReg);
2167 Prev = R;
2168 }
2169 Register AndReg = MRI.createVirtualRegister(&AVR::LD8RegClass);
2170 BuildMI(*BB, MI, dl, TII.get(AVR::ANDIRdK), AndReg)
2171 .addReg(SwapReg)
2172 .addImm(ShiftLeft ? 0xf0 : 0x0f);
2173 if (I != 0) {
2174 Register R = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2175 BuildMI(*BB, MI, dl, TII.get(AVR::EORRdRr), R)
2176 .addReg(Prev)
2177 .addReg(AndReg);
2178 size_t PrevIdx = ShiftLeft ? Idx - 1 : Idx + 1;
2179 Regs[PrevIdx] = std::pair(R, 0);
2180 }
2181 Prev = AndReg;
2182 Regs[Idx] = std::pair(AndReg, 0);
2183 }
2184 ShiftAmt -= 4;
2185 }
2186
2187 // Shift by one. This is the fallback that always works, and the shift
2188 // operation that is used for 1, 2, and 3 bit shifts.
2189 while (ShiftLeft && ShiftAmt) {
2190 // Shift one to the left.
2191 for (ssize_t I = Regs.size() - 1; I >= 0; I--) {
2192 Register Out = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2193 Register In = Regs[I].first;
2194 Register InSubreg = Regs[I].second;
2195 if (I == (ssize_t)Regs.size() - 1) { // first iteration
2196 BuildMI(*BB, MI, dl, TII.get(AVR::ADDRdRr), Out)
2197 .addReg(In, {}, InSubreg)
2198 .addReg(In, {}, InSubreg);
2199 } else {
2200 BuildMI(*BB, MI, dl, TII.get(AVR::ADCRdRr), Out)
2201 .addReg(In, {}, InSubreg)
2202 .addReg(In, {}, InSubreg);
2203 }
2204 Regs[I] = std::pair(Out, 0);
2205 }
2206 ShiftAmt--;
2207 }
2208 while (!ShiftLeft && ShiftAmt) {
2209 // Shift one to the right.
2210 for (size_t I = 0; I < Regs.size(); I++) {
2211 Register Out = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2212 Register In = Regs[I].first;
2213 Register InSubreg = Regs[I].second;
2214 if (I == 0) {
2215 unsigned Opc = ArithmeticShift ? AVR::ASRRd : AVR::LSRRd;
2216 BuildMI(*BB, MI, dl, TII.get(Opc), Out).addReg(In, {}, InSubreg);
2217 } else {
2218 BuildMI(*BB, MI, dl, TII.get(AVR::RORRd), Out).addReg(In, {}, InSubreg);
2219 }
2220 Regs[I] = std::pair(Out, 0);
2221 }
2222 ShiftAmt--;
2223 }
2224
2225 if (ShiftAmt != 0) {
2226 llvm_unreachable("don't know how to shift!"); // sanity check
2227 }
2228}
2229
2230// Do a wide (32-bit) shift.
2231MachineBasicBlock *
2232AVRTargetLowering::insertWideShift(MachineInstr &MI,
2233 MachineBasicBlock *BB) const {
2234 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
2235 const DebugLoc &dl = MI.getDebugLoc();
2236
2237 // How much to shift to the right (meaning: a negative number indicates a left
2238 // shift).
2239 int64_t ShiftAmt = MI.getOperand(4).getImm();
2241 switch (MI.getOpcode()) {
2242 case AVR::Lsl32:
2243 Opc = ISD::SHL;
2244 break;
2245 case AVR::Lsr32:
2246 Opc = ISD::SRL;
2247 break;
2248 case AVR::Asr32:
2249 Opc = ISD::SRA;
2250 break;
2251 }
2252
2253 // Read the input registers, with the most significant register at index 0.
2254 std::array<std::pair<Register, int>, 4> Registers = {
2255 std::pair(MI.getOperand(3).getReg(), AVR::sub_hi),
2256 std::pair(MI.getOperand(3).getReg(), AVR::sub_lo),
2257 std::pair(MI.getOperand(2).getReg(), AVR::sub_hi),
2258 std::pair(MI.getOperand(2).getReg(), AVR::sub_lo),
2259 };
2260
2261 // Do the shift. The registers are modified in-place.
2262 insertMultibyteShift(MI, BB, Registers, Opc, ShiftAmt);
2263
2264 // Combine the 8-bit registers into 16-bit register pairs.
2265 // This done either from LSB to MSB or from MSB to LSB, depending on the
2266 // shift. It's an optimization so that the register allocator will use the
2267 // fewest movs possible (which order we use isn't a correctness issue, just an
2268 // optimization issue).
2269 // - lsl prefers starting from the most significant byte (2nd case).
2270 // - lshr prefers starting from the least significant byte (1st case).
2271 // - for ashr it depends on the number of shifted bytes.
2272 // Some shift operations still don't get the most optimal mov sequences even
2273 // with this distinction.
2274 // TODO: Figure out why and try to fix it (but we're
2275 // already equal to or faster than avr-gcc in all cases except ashr 8).
2276 if (Opc != ISD::SHL &&
2277 (Opc != ISD::SRA || (ShiftAmt < 16 || ShiftAmt >= 22))) {
2278 // Use the resulting registers starting with the least significant byte.
2279 BuildMI(*BB, MI, dl, TII.get(AVR::REG_SEQUENCE), MI.getOperand(0).getReg())
2280 .addReg(Registers[3].first, {}, Registers[3].second)
2281 .addImm(AVR::sub_lo)
2282 .addReg(Registers[2].first, {}, Registers[2].second)
2283 .addImm(AVR::sub_hi);
2284 BuildMI(*BB, MI, dl, TII.get(AVR::REG_SEQUENCE), MI.getOperand(1).getReg())
2285 .addReg(Registers[1].first, {}, Registers[1].second)
2286 .addImm(AVR::sub_lo)
2287 .addReg(Registers[0].first, {}, Registers[0].second)
2288 .addImm(AVR::sub_hi);
2289 } else {
2290 // Use the resulting registers starting with the most significant byte.
2291 BuildMI(*BB, MI, dl, TII.get(AVR::REG_SEQUENCE), MI.getOperand(1).getReg())
2292 .addReg(Registers[0].first, {}, Registers[0].second)
2293 .addImm(AVR::sub_hi)
2294 .addReg(Registers[1].first, {}, Registers[1].second)
2295 .addImm(AVR::sub_lo);
2296 BuildMI(*BB, MI, dl, TII.get(AVR::REG_SEQUENCE), MI.getOperand(0).getReg())
2297 .addReg(Registers[2].first, {}, Registers[2].second)
2298 .addImm(AVR::sub_hi)
2299 .addReg(Registers[3].first, {}, Registers[3].second)
2300 .addImm(AVR::sub_lo);
2301 }
2302
2303 // Remove the pseudo instruction.
2304 MI.eraseFromParent();
2305 return BB;
2306}
2307
2309 if (I->getOpcode() == AVR::COPY) {
2310 Register SrcReg = I->getOperand(1).getReg();
2311 return (SrcReg == AVR::R0 || SrcReg == AVR::R1);
2312 }
2313
2314 return false;
2315}
2316
2317// The mul instructions wreak havock on our zero_reg R1. We need to clear it
2318// after the result has been evacuated. This is probably not the best way to do
2319// it, but it works for now.
2320MachineBasicBlock *AVRTargetLowering::insertMul(MachineInstr &MI,
2321 MachineBasicBlock *BB) const {
2322 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
2324 ++I; // in any case insert *after* the mul instruction
2325 if (isCopyMulResult(I))
2326 ++I;
2327 if (isCopyMulResult(I))
2328 ++I;
2329 BuildMI(*BB, I, MI.getDebugLoc(), TII.get(AVR::EORRdRr), AVR::R1)
2330 .addReg(AVR::R1)
2331 .addReg(AVR::R1);
2332 return BB;
2333}
2334
2335// Insert a read from the zero register.
2337AVRTargetLowering::insertCopyZero(MachineInstr &MI,
2338 MachineBasicBlock *BB) const {
2339 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
2341 BuildMI(*BB, I, MI.getDebugLoc(), TII.get(AVR::COPY))
2342 .add(MI.getOperand(0))
2343 .addReg(Subtarget.getZeroRegister());
2344 MI.eraseFromParent();
2345 return BB;
2346}
2347
2348// Lower atomicrmw operation to disable interrupts, do operation, and restore
2349// interrupts. This works because all AVR microcontrollers are single core.
2350MachineBasicBlock *AVRTargetLowering::insertAtomicArithmeticOp(
2351 MachineInstr &MI, MachineBasicBlock *BB, unsigned Opcode, int Width) const {
2352 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
2353 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
2355 DebugLoc dl = MI.getDebugLoc();
2356
2357 // Example instruction sequence, for an atomic 8-bit add:
2358 // ldi r25, 5
2359 // in r0, SREG
2360 // cli
2361 // ld r24, X
2362 // add r25, r24
2363 // st X, r25
2364 // out SREG, r0
2365
2366 const TargetRegisterClass *RC =
2367 (Width == 8) ? &AVR::GPR8RegClass : &AVR::DREGSNOZRegClass;
2368 unsigned LoadOpcode = (Width == 8) ? AVR::LDRdPtr : AVR::LDWRdPtr;
2369 unsigned StoreOpcode = (Width == 8) ? AVR::STPtrRr : AVR::STWPtrRr;
2370
2371 // Disable interrupts.
2372 BuildMI(*BB, I, dl, TII.get(AVR::INRdA), Subtarget.getTmpRegister())
2373 .addImm(Subtarget.getIORegSREG());
2374 BuildMI(*BB, I, dl, TII.get(AVR::BCLRs)).addImm(7);
2375
2376 // Load the original value.
2377 BuildMI(*BB, I, dl, TII.get(LoadOpcode), MI.getOperand(0).getReg())
2378 .add(MI.getOperand(1));
2379
2380 // Do the arithmetic operation.
2381 Register Result = MRI.createVirtualRegister(RC);
2382 BuildMI(*BB, I, dl, TII.get(Opcode), Result)
2383 .addReg(MI.getOperand(0).getReg())
2384 .add(MI.getOperand(2));
2385
2386 // Store the result.
2387 BuildMI(*BB, I, dl, TII.get(StoreOpcode))
2388 .add(MI.getOperand(1))
2389 .addReg(Result);
2390
2391 // Restore interrupts.
2392 BuildMI(*BB, I, dl, TII.get(AVR::OUTARr))
2393 .addImm(Subtarget.getIORegSREG())
2394 .addReg(Subtarget.getTmpRegister());
2395
2396 // Remove the pseudo instruction.
2397 MI.eraseFromParent();
2398 return BB;
2399}
2400
2403 MachineBasicBlock *MBB) const {
2404 int Opc = MI.getOpcode();
2405 const AVRSubtarget &STI = MBB->getParent()->getSubtarget<AVRSubtarget>();
2406
2407 // Pseudo shift instructions with a non constant shift amount are expanded
2408 // into a loop.
2409 switch (Opc) {
2410 case AVR::Lsl8:
2411 case AVR::Lsl16:
2412 case AVR::Lsr8:
2413 case AVR::Lsr16:
2414 case AVR::Rol8:
2415 case AVR::Rol16:
2416 case AVR::Ror8:
2417 case AVR::Ror16:
2418 case AVR::Asr8:
2419 case AVR::Asr16:
2420 return insertShift(MI, MBB, STI.hasTinyEncoding());
2421 case AVR::Lsl32:
2422 case AVR::Lsr32:
2423 case AVR::Asr32:
2424 return insertWideShift(MI, MBB);
2425 case AVR::MULRdRr:
2426 case AVR::MULSRdRr:
2427 return insertMul(MI, MBB);
2428 case AVR::CopyZero:
2429 return insertCopyZero(MI, MBB);
2430 case AVR::AtomicLoadAdd8:
2431 return insertAtomicArithmeticOp(MI, MBB, AVR::ADDRdRr, 8);
2432 case AVR::AtomicLoadAdd16:
2433 return insertAtomicArithmeticOp(MI, MBB, AVR::ADDWRdRr, 16);
2434 case AVR::AtomicLoadSub8:
2435 return insertAtomicArithmeticOp(MI, MBB, AVR::SUBRdRr, 8);
2436 case AVR::AtomicLoadSub16:
2437 return insertAtomicArithmeticOp(MI, MBB, AVR::SUBWRdRr, 16);
2438 case AVR::AtomicLoadAnd8:
2439 return insertAtomicArithmeticOp(MI, MBB, AVR::ANDRdRr, 8);
2440 case AVR::AtomicLoadAnd16:
2441 return insertAtomicArithmeticOp(MI, MBB, AVR::ANDWRdRr, 16);
2442 case AVR::AtomicLoadOr8:
2443 return insertAtomicArithmeticOp(MI, MBB, AVR::ORRdRr, 8);
2444 case AVR::AtomicLoadOr16:
2445 return insertAtomicArithmeticOp(MI, MBB, AVR::ORWRdRr, 16);
2446 case AVR::AtomicLoadXor8:
2447 return insertAtomicArithmeticOp(MI, MBB, AVR::EORRdRr, 8);
2448 case AVR::AtomicLoadXor16:
2449 return insertAtomicArithmeticOp(MI, MBB, AVR::EORWRdRr, 16);
2450 }
2451
2452 assert((Opc == AVR::Select16 || Opc == AVR::Select8) &&
2453 "Unexpected instr type to insert");
2454
2455 const AVRInstrInfo &TII = (const AVRInstrInfo &)*MI.getParent()
2456 ->getParent()
2457 ->getSubtarget()
2458 .getInstrInfo();
2459 DebugLoc dl = MI.getDebugLoc();
2460
2461 // To "insert" a SELECT instruction, we insert the diamond
2462 // control-flow pattern. The incoming instruction knows the
2463 // destination vreg to set, the condition code register to branch
2464 // on, the true/false values to select between, and a branch opcode
2465 // to use.
2466
2467 MachineFunction *MF = MBB->getParent();
2468 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
2469 MachineBasicBlock *FallThrough = MBB->getFallThrough();
2470
2471 // If the current basic block falls through to another basic block,
2472 // we must insert an unconditional branch to the fallthrough destination
2473 // if we are to insert basic blocks at the prior fallthrough point.
2474 if (FallThrough != nullptr) {
2475 BuildMI(MBB, dl, TII.get(AVR::RJMPk)).addMBB(FallThrough);
2476 }
2477
2478 MachineBasicBlock *trueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
2479 MachineBasicBlock *falseMBB = MF->CreateMachineBasicBlock(LLVM_BB);
2480
2482 for (I = MF->begin(); I != MF->end() && &(*I) != MBB; ++I)
2483 ;
2484 if (I != MF->end())
2485 ++I;
2486 MF->insert(I, trueMBB);
2487 MF->insert(I, falseMBB);
2488
2489 // Set the call frame size on entry to the new basic blocks.
2490 unsigned CallFrameSize = TII.getCallFrameSizeAt(MI);
2491 trueMBB->setCallFrameSize(CallFrameSize);
2492 falseMBB->setCallFrameSize(CallFrameSize);
2493
2494 // Transfer remaining instructions and all successors of the current
2495 // block to the block which will contain the Phi node for the
2496 // select.
2497 trueMBB->splice(trueMBB->begin(), MBB,
2498 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
2500
2501 AVRCC::CondCodes CC = (AVRCC::CondCodes)MI.getOperand(3).getImm();
2502 BuildMI(MBB, dl, TII.getBrCond(CC)).addMBB(trueMBB);
2503 BuildMI(MBB, dl, TII.get(AVR::RJMPk)).addMBB(falseMBB);
2504 MBB->addSuccessor(falseMBB);
2505 MBB->addSuccessor(trueMBB);
2506
2507 // Unconditionally flow back to the true block
2508 BuildMI(falseMBB, dl, TII.get(AVR::RJMPk)).addMBB(trueMBB);
2509 falseMBB->addSuccessor(trueMBB);
2510
2511 // Set up the Phi node to determine where we came from
2512 BuildMI(*trueMBB, trueMBB->begin(), dl, TII.get(AVR::PHI),
2513 MI.getOperand(0).getReg())
2514 .addReg(MI.getOperand(1).getReg())
2515 .addMBB(MBB)
2516 .addReg(MI.getOperand(2).getReg())
2517 .addMBB(falseMBB);
2518
2519 MI.eraseFromParent(); // The pseudo instruction is gone now.
2520 return trueMBB;
2521}
2522
2523//===----------------------------------------------------------------------===//
2524// Inline Asm Support
2525//===----------------------------------------------------------------------===//
2526
2529 if (Constraint.size() == 1) {
2530 // See http://www.nongnu.org/avr-libc/user-manual/inline_asm.html
2531 switch (Constraint[0]) {
2532 default:
2533 break;
2534 case 'a': // Simple upper registers
2535 case 'b': // Base pointer registers pairs
2536 case 'd': // Upper register
2537 case 'l': // Lower registers
2538 case 'e': // Pointer register pairs
2539 case 'q': // Stack pointer register
2540 case 'r': // Any register
2541 case 'w': // Special upper register pairs
2542 return C_RegisterClass;
2543 case 't': // Temporary register
2544 case 'x':
2545 case 'X': // Pointer register pair X
2546 case 'y':
2547 case 'Y': // Pointer register pair Y
2548 case 'z':
2549 case 'Z': // Pointer register pair Z
2550 return C_Register;
2551 case 'Q': // A memory address based on Y or Z pointer with displacement.
2552 return C_Memory;
2553 case 'G': // Floating point constant
2554 case 'I': // 6-bit positive integer constant
2555 case 'J': // 6-bit negative integer constant
2556 case 'K': // Integer constant (Range: 2)
2557 case 'L': // Integer constant (Range: 0)
2558 case 'M': // 8-bit integer constant
2559 case 'N': // Integer constant (Range: -1)
2560 case 'O': // Integer constant (Range: 8, 16, 24)
2561 case 'P': // Integer constant (Range: 1)
2562 case 'R': // Integer constant (Range: -6 to 5)x
2563 return C_Immediate;
2564 }
2565 }
2566
2567 return TargetLowering::getConstraintType(Constraint);
2568}
2569
2572 // Not sure if this is actually the right thing to do, but we got to do
2573 // *something* [agnat]
2574 switch (ConstraintCode[0]) {
2575 case 'Q':
2577 }
2578 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
2579}
2580
2583 AsmOperandInfo &info, const char *constraint) const {
2585 Value *CallOperandVal = info.CallOperandVal;
2586
2587 // If we don't have a value, we can't do a match,
2588 // but allow it at the lowest weight.
2589 // (this behaviour has been copied from the ARM backend)
2590 if (!CallOperandVal) {
2591 return CW_Default;
2592 }
2593
2594 // Look at the constraint type.
2595 switch (*constraint) {
2596 default:
2598 break;
2599 case 'd':
2600 case 'r':
2601 case 'l':
2603 break;
2604 case 'a':
2605 case 'b':
2606 case 'e':
2607 case 'q':
2608 case 't':
2609 case 'w':
2610 case 'x':
2611 case 'X':
2612 case 'y':
2613 case 'Y':
2614 case 'z':
2615 case 'Z':
2617 break;
2618 case 'G':
2619 if (const ConstantFP *C = dyn_cast<ConstantFP>(CallOperandVal)) {
2620 if (C->isZero()) {
2622 }
2623 }
2624 break;
2625 case 'I':
2626 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2627 if (isUInt<6>(C->getZExtValue())) {
2629 }
2630 }
2631 break;
2632 case 'J':
2633 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2634 if ((C->getSExtValue() >= -63) && (C->getSExtValue() <= 0)) {
2636 }
2637 }
2638 break;
2639 case 'K':
2640 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2641 if (C->getZExtValue() == 2) {
2643 }
2644 }
2645 break;
2646 case 'L':
2647 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2648 if (C->getZExtValue() == 0) {
2650 }
2651 }
2652 break;
2653 case 'M':
2654 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2655 if (isUInt<8>(C->getZExtValue())) {
2657 }
2658 }
2659 break;
2660 case 'N':
2661 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2662 if (C->getSExtValue() == -1) {
2664 }
2665 }
2666 break;
2667 case 'O':
2668 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2669 if ((C->getZExtValue() == 8) || (C->getZExtValue() == 16) ||
2670 (C->getZExtValue() == 24)) {
2672 }
2673 }
2674 break;
2675 case 'P':
2676 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2677 if (C->getZExtValue() == 1) {
2679 }
2680 }
2681 break;
2682 case 'R':
2683 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2684 if ((C->getSExtValue() >= -6) && (C->getSExtValue() <= 5)) {
2686 }
2687 }
2688 break;
2689 case 'Q':
2690 weight = CW_Memory;
2691 break;
2692 }
2693
2694 return weight;
2695}
2696
2697std::pair<unsigned, const TargetRegisterClass *>
2699 StringRef Constraint,
2700 MVT VT) const {
2701 if (Constraint.size() == 1) {
2702 switch (Constraint[0]) {
2703 case 'a': // Simple upper registers r16..r23.
2704 if (VT == MVT::i8)
2705 return std::make_pair(0U, &AVR::LD8loRegClass);
2706 else if (VT == MVT::i16)
2707 return std::make_pair(0U, &AVR::DREGSLD8loRegClass);
2708 break;
2709 case 'b': // Base pointer registers: y, z.
2710 if (VT == MVT::i8 || VT == MVT::i16)
2711 return std::make_pair(0U, &AVR::PTRDISPREGSRegClass);
2712 break;
2713 case 'd': // Upper registers r16..r31.
2714 if (VT == MVT::i8)
2715 return std::make_pair(0U, &AVR::LD8RegClass);
2716 else if (VT == MVT::i16)
2717 return std::make_pair(0U, &AVR::DLDREGSRegClass);
2718 break;
2719 case 'l': // Lower registers r0..r15.
2720 if (VT == MVT::i8)
2721 return std::make_pair(0U, &AVR::GPR8loRegClass);
2722 else if (VT == MVT::i16)
2723 return std::make_pair(0U, &AVR::DREGSloRegClass);
2724 break;
2725 case 'e': // Pointer register pairs: x, y, z.
2726 if (VT == MVT::i8 || VT == MVT::i16)
2727 return std::make_pair(0U, &AVR::PTRREGSRegClass);
2728 break;
2729 case 'q': // Stack pointer register: SPH:SPL.
2730 return std::make_pair(0U, &AVR::GPRSPRegClass);
2731 case 'r': // Any register: r0..r31.
2732 if (VT == MVT::i8)
2733 return std::make_pair(0U, &AVR::GPR8RegClass);
2734 else if (VT == MVT::i16)
2735 return std::make_pair(0U, &AVR::DREGSRegClass);
2736 break;
2737 case 't': // Temporary register: r0.
2738 if (VT == MVT::i8)
2739 return std::make_pair(unsigned(Subtarget.getTmpRegister()),
2740 &AVR::GPR8RegClass);
2741 break;
2742 case 'w': // Special upper register pairs: r24, r26, r28, r30.
2743 if (VT == MVT::i8 || VT == MVT::i16)
2744 return std::make_pair(0U, &AVR::IWREGSRegClass);
2745 break;
2746 case 'x': // Pointer register pair X: r27:r26.
2747 case 'X':
2748 if (VT == MVT::i8 || VT == MVT::i16)
2749 return std::make_pair(unsigned(AVR::R27R26), &AVR::PTRREGSRegClass);
2750 break;
2751 case 'y': // Pointer register pair Y: r29:r28.
2752 case 'Y':
2753 if (VT == MVT::i8 || VT == MVT::i16)
2754 return std::make_pair(unsigned(AVR::R29R28), &AVR::PTRREGSRegClass);
2755 break;
2756 case 'z': // Pointer register pair Z: r31:r30.
2757 case 'Z':
2758 if (VT == MVT::i8 || VT == MVT::i16)
2759 return std::make_pair(unsigned(AVR::R31R30), &AVR::PTRREGSRegClass);
2760 break;
2761 default:
2762 break;
2763 }
2764 }
2765
2767 Subtarget.getRegisterInfo(), Constraint, VT);
2768}
2769
2771 StringRef Constraint,
2772 std::vector<SDValue> &Ops,
2773 SelectionDAG &DAG) const {
2774 SDValue Result;
2775 SDLoc DL(Op);
2776 EVT Ty = Op.getValueType();
2777
2778 // Currently only support length 1 constraints.
2779 if (Constraint.size() != 1) {
2780 return;
2781 }
2782
2783 char ConstraintLetter = Constraint[0];
2784 switch (ConstraintLetter) {
2785 default:
2786 break;
2787 // Deal with integers first:
2788 case 'I':
2789 case 'J':
2790 case 'K':
2791 case 'L':
2792 case 'M':
2793 case 'N':
2794 case 'O':
2795 case 'P':
2796 case 'R': {
2798 if (!C) {
2799 return;
2800 }
2801
2802 int64_t CVal64 = C->getSExtValue();
2803 uint64_t CUVal64 = C->getZExtValue();
2804 switch (ConstraintLetter) {
2805 case 'I': // 0..63
2806 if (!isUInt<6>(CUVal64))
2807 return;
2808 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
2809 break;
2810 case 'J': // -63..0
2811 if (CVal64 < -63 || CVal64 > 0)
2812 return;
2813 Result = DAG.getTargetConstant(CVal64, DL, Ty);
2814 break;
2815 case 'K': // 2
2816 if (CUVal64 != 2)
2817 return;
2818 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
2819 break;
2820 case 'L': // 0
2821 if (CUVal64 != 0)
2822 return;
2823 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
2824 break;
2825 case 'M': // 0..255
2826 if (!isUInt<8>(CUVal64))
2827 return;
2828 // i8 type may be printed as a negative number,
2829 // e.g. 254 would be printed as -2,
2830 // so we force it to i16 at least.
2831 if (Ty.getSimpleVT() == MVT::i8) {
2832 Ty = MVT::i16;
2833 }
2834 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
2835 break;
2836 case 'N': // -1
2837 if (CVal64 != -1)
2838 return;
2839 Result = DAG.getTargetConstant(CVal64, DL, Ty);
2840 break;
2841 case 'O': // 8, 16, 24
2842 if (CUVal64 != 8 && CUVal64 != 16 && CUVal64 != 24)
2843 return;
2844 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
2845 break;
2846 case 'P': // 1
2847 if (CUVal64 != 1)
2848 return;
2849 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
2850 break;
2851 case 'R': // -6..5
2852 if (CVal64 < -6 || CVal64 > 5)
2853 return;
2854 Result = DAG.getTargetConstant(CVal64, DL, Ty);
2855 break;
2856 }
2857
2858 break;
2859 }
2860 case 'G':
2862 if (!FC || !FC->isZero())
2863 return;
2864 // Soften float to i8 0
2865 Result = DAG.getTargetConstant(0, DL, MVT::i8);
2866 break;
2867 }
2868
2869 if (Result.getNode()) {
2870 Ops.push_back(Result);
2871 return;
2872 }
2873
2874 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
2875}
2876
2878 const MachineFunction &MF) const {
2879 Register Reg;
2880
2881 if (VT == LLT::scalar(8)) {
2883 .Case("r0", AVR::R0)
2884 .Case("r1", AVR::R1)
2885 .Default(0);
2886 } else {
2888 .Case("r0", AVR::R1R0)
2889 .Case("sp", AVR::SP)
2890 .Default(0);
2891 }
2892
2893 if (Reg)
2894 return Reg;
2895
2897 Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
2898}
2899
2900} // end of namespace llvm
return SDValue()
const AArch64Subtarget & Subtarget
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
uint64_t uint64_t
uint64_t Imm
AMDGPU Reserve WWM Registers
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
hexagon merge activate weight
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
lazy value info
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
MachineInstr *& Lo
This file implements the StringSwitch template, which mimics a switch() statement whose cases are str...
Value * RHS
Value * LHS
Utilities related to the AVR instruction set.
A specific AVR target MCU.
Register getZeroRegister() const
void ReplaceNodeResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const override
Replace a node with an illegal result type with a new node built out of custom code.
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override
This callback is invoked for operations that are unsupported by the target, which are registered to u...
bool getPreIndexedAddressParts(SDNode *N, SDValue &Base, SDValue &Offset, ISD::MemIndexedMode &AM, SelectionDAG &DAG) const override
Returns true by value, base pointer and offset pointer and addressing mode by reference if the node's...
std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const override
Given a physical register constraint (e.g.
MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const override
This method should be implemented by targets that mark instructions with the 'usesCustomInserter' fla...
ConstraintType getConstraintType(StringRef Constraint) const override
Given a constraint, return the type of constraint it is for this target.
const AVRSubtarget & Subtarget
InlineAsm::ConstraintCode getInlineAsmMemConstraint(StringRef ConstraintCode) const override
bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I=nullptr) const override
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const override
Examine constraint string and operand type and determine a weight value.
bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const override
Return true if folding a constant offset with the given GlobalAddress is legal.
Register getRegisterByName(const char *RegName, LLT VT, const MachineFunction &MF) const override
Return the register ID of the name passed in.
AVRTargetLowering(const AVRTargetMachine &TM, const AVRSubtarget &STI)
void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const override
Lower the specified operand into the Ops vector.
EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const override
Return the ValueType of the result of SETCC operations.
bool getPostIndexedAddressParts(SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset, ISD::MemIndexedMode &AM, SelectionDAG &DAG) const override
Returns true by value, base pointer and offset pointer and addressing mode by reference if this node ...
A generic AVR implementation.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
LLVM Basic Block Representation.
Definition BasicBlock.h:62
CCState - This class holds information needed while lowering arguments and return values.
MCRegister AllocateReg(MCPhysReg Reg)
AllocateReg - Attempt to allocate one register.
LLVMContext & getContext() const
int64_t AllocateStack(unsigned Size, Align Alignment)
AllocateStack - Allocate a chunk of stack space with the specified size and alignment.
void addLoc(const CCValAssign &V)
static CCValAssign getReg(unsigned ValNo, MVT ValVT, MCRegister Reg, MVT LocVT, LocInfo HTP, bool IsCustom=false)
static CCValAssign getMem(unsigned ValNo, MVT ValVT, int64_t Offset, MVT LocVT, LocInfo HTP, bool IsCustom=false)
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
This is the shared class of boolean and integer constants.
Definition Constants.h:87
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI Align getABITypeAlign(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
LLVM_ABI TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
A debug info location.
Definition DebugLoc.h:127
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
This class is used to represent ISD::LOAD nodes.
Machine Value Type.
static auto integer_valuetypes()
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
void setCallFrameSize(unsigned N)
Set the call frame size on entry to this basic block.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
void setFrameAddressIsTaken(bool T)
void setReturnAddressIsTaken(bool s)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
BasicBlockListType::iterator iterator
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
MutableArrayRef< T > slice(size_t N, size_t M) const
Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:372
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
SDValue getValue(unsigned R) const
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
MachineFunction & getMachineFunction() const
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This class is used to represent ISD::STORE nodes.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:462
TargetInstrInfo - Interface to description of machine instruction set.
void setBooleanVectorContents(BooleanContent Ty)
Specify how the target extends the result of a vector boolean value from a vector of i1 to a wider ty...
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action)
Indicate that the specified operation does not work with the specified type and indicate what to do a...
void setIndexedLoadAction(ArrayRef< unsigned > IdxModes, MVT VT, LegalizeAction Action)
Indicate that the specified indexed load does or does not work with the specified type and indicate w...
void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits)
Set the maximum atomic operation size supported by the backend.
void setMinFunctionAlignment(Align Alignment)
Set the target's minimum function alignment.
void setBooleanContents(BooleanContent Ty)
Specify how the target extends the result of a boolean value from i1 to a wider type.
void computeRegisterProperties(const TargetRegisterInfo *TRI)
Once all of the register classes are added, this allows us to compute derived properties we expose.
void addRegisterClass(MVT VT, const TargetRegisterClass *RC)
Add the specified register class as an available regclass for the specified value type.
void setIndexedStoreAction(ArrayRef< unsigned > IdxModes, MVT VT, LegalizeAction Action)
Indicate that the specified indexed store does or does not work with the specified type and indicate ...
void setSupportsUnalignedAtomics(bool UnalignedSupported)
Sets whether unaligned atomic operations are supported.
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
void setMinimumJumpTableEntries(unsigned Val)
Indicate the minimum number of blocks to generate jump tables.
void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified truncating store does not work with the specified type and indicate what ...
void setStackPointerRegisterToSaveRestore(Register R)
If set to a physical register, this specifies the register that llvm.savestack/llvm....
void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified load with extension does not work with the specified type and indicate wh...
std::vector< ArgListEntry > ArgListTy
void setSchedulingPreference(Sched::Preference Pref)
Specify the target scheduling preference.
virtual InlineAsm::ConstraintCode getInlineAsmMemConstraint(StringRef ConstraintCode) const
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
virtual ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const
Examine constraint string and operand type and determine a weight value.
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
TargetLowering(const TargetLowering &)=delete
virtual void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const
Lower the specified operand into the Ops vector.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
CondCodes
AVR specific condition codes.
@ COND_SH
Unsigned same or higher.
@ COND_GE
Greater than or equal.
@ COND_MI
Minus.
@ COND_LO
Unsigned lower.
@ COND_LT
Less than.
@ COND_PL
Plus.
@ COND_EQ
Equal.
@ COND_NE
Not equal.
bool isProgramMemoryAccess(MemSDNode const *N)
Definition AVR.h:106
@ ProgramMemory
Definition AVR.h:76
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ AVR_BUILTIN
Used for special AVR rtlib functions which have an "optimized" convention to preserve registers.
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:43
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:851
@ STACKRESTORE
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain.
@ STACKSAVE
STACKSAVE - STACKSAVE has one operand, an input chain.
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:277
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:811
@ VAEND
VAEND, VASTART - VAEND and VASTART have three operands: an input chain, pointer, and a SRCVALUE.
@ ADDC
Carry-setting nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:296
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:885
@ GlobalAddress
Definition ISDOpcodes.h:90
@ SDIVREM
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition ISDOpcodes.h:282
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:256
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:876
@ BR_CC
BR_CC - Conditional branch.
@ BR_JT
BR_JT - Jumptable branch.
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:828
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:249
@ VACOPY
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer,...
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:720
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:793
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:882
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:843
@ ATOMIC_CMP_SWAP
Val, OUTCHAIN = ATOMIC_CMP_SWAP(INCHAIN, ptr, cmp, swap) For double-word atomic operations: ValLo,...
@ DYNAMIC_STACKALLOC
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary.
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:920
@ FRAMEADDR
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG.
Definition ISDOpcodes.h:112
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:763
@ ADDE
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:306
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ ATOMIC_SWAP
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN,...
@ INLINEASM
INLINEASM - Represents an inline asm block.
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:888
@ VAARG
VAARG - VAARG has four operands: an input chain, a pointer, a SRCVALUE, and the alignment.
@ BRCOND
BRCOND - Conditional branch.
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:865
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:64
MemIndexedMode
MemIndexedMode enum - This enum defines the load / store indexed addressing modes.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
static void analyzeReturnValues(const SmallVectorImpl< ArgT > &Args, CCState &CCInfo, bool Tiny)
Analyze incoming and outgoing value of returning from a function.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Undef
Value of the register doesn't matter.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
static const MCPhysReg RegList16Tiny[]
constexpr bool has_single_bit(T Value) noexcept
Definition bit.h:149
static const MCPhysReg RegList8Tiny[]
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
static void analyzeArguments(TargetLowering::CallLoweringInfo *CLI, const Function *F, const DataLayout *TD, const SmallVectorImpl< ArgT > &Args, SmallVectorImpl< CCValAssign > &ArgLocs, CCState &CCInfo, bool Tiny)
Analyze incoming and outgoing function arguments.
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
static const MCPhysReg RegList16AVR[]
@ Sub
Subtraction of integers.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
static unsigned getTotalArgumentsSizeInBytes(const SmallVectorImpl< ArgT > &Args)
Count the total number of bytes needed to pass or return these arguments.
DWARFExpression::Operation Op
static AVRCC::CondCodes intCCToAVRCC(ISD::CondCode CC)
IntCCToAVRCC - Convert a DAG integer condition code to an AVR CC.
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
static bool isCopyMulResult(MachineBasicBlock::iterator const &I)
static void insertMultibyteShift(MachineInstr &MI, MachineBasicBlock *BB, MutableArrayRef< std::pair< Register, int > > Regs, ISD::NodeType Opc, int64_t ShiftAmt)
static const MCPhysReg RegList8AVR[]
Registers for calling conventions, ordered in reverse as required by ABI.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Extended Value Type.
Definition ValueTypes.h:35
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:191
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
static LLVM_ABI MachinePointerInfo getStack(MachineFunction &MF, int64_t Offset, uint8_t ID=0)
Stack pointer relative access.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg + ScalableOffset*...
This contains information for each constraint that we are lowering.
This structure contains all information that is necessary for lowering calls.