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
523 SDValue Callee =
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.
550 SDValue Result =
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 = cast<CondCodeSDNode>(Op.getOperand(1))->get();
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 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
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 = cast<CondCodeSDNode>(Op.getOperand(2))->get();
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).
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.
1008 //
1009 // The return address is pushed most significant byte first, hence it is
1010 // stored big-endian: [SP_entry + 1] is the high byte and [SP_entry + 2] the
1011 // low byte. This is why avr-gcc has to swap the two bytes it reads for
1012 // __builtin_return_address(0).
1013 //
1014 // Walking the frame chain is not possible, because the distance between the
1015 // frame base and the slot holding the caller's return address depends on the
1016 // caller's frame size, which is not known here. This is also what avr-gcc
1017 // does for __builtin_return_address(1), which returns zero.
1018 if (Op.getConstantOperandVal(0) > 0)
1019 // Use the legalizer's default expansion, which is to return 0 (what this
1020 // function is documented to do).
1021 return SDValue();
1022
1023 MachineFunction &MF = DAG.getMachineFunction();
1024 MachineFrameInfo &MFI = MF.getFrameInfo();
1025 // Mark return address as taken, so that during frame lowering we're forced to
1026 // emit frame pointer register (R29R28) we rely on here.
1027 MFI.setReturnAddressIsTaken(true);
1028
1029 SDLoc DL(Op);
1030 EVT PtrVT = getPointerTy(DAG.getDataLayout());
1031
1032 // A call pushes as many bytes as the program counter is wide: three on
1033 // devices with a 22-bit PC (the ones providing EIJMP/EICALL), two elsewhere.
1034 // Only the two low bytes of the return address are returned, so on the former
1035 // they are found one byte higher up.
1036 int PCWidth = Subtarget.hasEIJMPCALL() ? 3 : 2;
1037
1038 // A fixed object at offset N is located at SP_entry + N + 3, so the two low
1039 // bytes of the return address are the fixed object at offset PCWidth - 4.
1040 // Note that a frame index can only be referenced through Y, so taking the
1041 // return address forces the function to have a frame pointer (see
1042 // AVRFrameLowering::hasFPImpl).
1043 int FI = MFI.CreateFixedObject(2, PCWidth - 4, true);
1044 SDValue Addr = DAG.getFrameIndex(FI, PtrVT);
1045
1046 // Load the two bytes separately and put them in the right halves of the
1047 // result, which is cheaper than loading a word and byte swapping it.
1048 SDValue Hi = DAG.getLoad(MVT::i8, DL, DAG.getEntryNode(), Addr,
1050 SDValue Lo =
1051 DAG.getLoad(MVT::i8, DL, DAG.getEntryNode(),
1052 DAG.getObjectPtrOffset(DL, Addr, TypeSize::getFixed(1)),
1054
1055 SDValue Res = DAG.getTargetInsertSubreg(AVR::sub_lo, DL, MVT::i16,
1056 DAG.getUNDEF(MVT::i16), Lo);
1057 return DAG.getTargetInsertSubreg(AVR::sub_hi, DL, MVT::i16, Res, Hi);
1058}
1059
1060/// Replace a node with an illegal result type
1061/// with a new node built out of custom code.
1064 SelectionDAG &DAG) const {
1065 SDLoc DL(N);
1066
1067 switch (N->getOpcode()) {
1068 case ISD::ADD: {
1069 // Convert add (x, imm) into sub (x, -imm).
1070 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
1071 SDValue Sub = DAG.getNode(
1072 ISD::SUB, DL, N->getValueType(0), N->getOperand(0),
1073 DAG.getConstant(-C->getAPIntValue(), DL, C->getValueType(0)));
1074 Results.push_back(Sub);
1075 }
1076 break;
1077 }
1078 default: {
1079 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1080
1081 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1082 Results.push_back(Res.getValue(I));
1083
1084 break;
1085 }
1086 }
1087}
1088
1089/// Return true if the addressing mode represented
1090/// by AM is legal for this target, for a load/store of the specified type.
1092 const AddrMode &AM, Type *Ty,
1093 unsigned AS,
1094 Instruction *I) const {
1095 int64_t Offs = AM.BaseOffs;
1096
1097 // Allow absolute addresses.
1098 if (AM.BaseGV && !AM.HasBaseReg && AM.Scale == 0 && Offs == 0) {
1099 return true;
1100 }
1101
1102 // Flash memory instructions only allow zero offsets.
1103 if (isa<PointerType>(Ty) && AS == AVR::ProgramMemory) {
1104 return false;
1105 }
1106
1107 // Allow reg+<6bit> offset.
1108 if (Offs < 0)
1109 Offs = -Offs;
1110 if (AM.BaseGV == nullptr && AM.HasBaseReg && AM.Scale == 0 &&
1111 isUInt<6>(Offs)) {
1112 return true;
1113 }
1114
1115 return false;
1116}
1117
1118/// Returns true by value, base pointer and
1119/// offset pointer and addressing mode by reference if the node's address
1120/// can be legally represented as pre-indexed load / store address.
1122 SDValue &Offset,
1124 SelectionDAG &DAG) const {
1125 EVT VT;
1126 const SDNode *Op;
1127 SDLoc DL(N);
1128
1129 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1130 VT = LD->getMemoryVT();
1131 Op = LD->getBasePtr().getNode();
1132 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
1133 return false;
1135 return false;
1136 }
1137 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1138 VT = ST->getMemoryVT();
1139 Op = ST->getBasePtr().getNode();
1141 return false;
1142 }
1143 } else {
1144 return false;
1145 }
1146
1147 if (VT != MVT::i8 && VT != MVT::i16) {
1148 return false;
1149 }
1150
1151 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) {
1152 return false;
1153 }
1154
1155 if (const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
1156 int RHSC = RHS->getSExtValue();
1157 if (Op->getOpcode() == ISD::SUB)
1158 RHSC = -RHSC;
1159
1160 if ((VT == MVT::i16 && RHSC != -2) || (VT == MVT::i8 && RHSC != -1)) {
1161 return false;
1162 }
1163
1164 Base = Op->getOperand(0);
1165 Offset = DAG.getSignedConstant(RHSC, DL, MVT::i8);
1166 AM = ISD::PRE_DEC;
1167
1168 return true;
1169 }
1170
1171 return false;
1172}
1173
1174/// Returns true by value, base pointer and
1175/// offset pointer and addressing mode by reference if this node can be
1176/// combined with a load / store to form a post-indexed load / store.
1178 SDValue &Base,
1179 SDValue &Offset,
1181 SelectionDAG &DAG) const {
1182 EVT VT;
1183 SDValue Ptr;
1184 SDLoc DL(N);
1185
1186 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1187 VT = LD->getMemoryVT();
1188 Ptr = LD->getBasePtr();
1189 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
1190 return false;
1191 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1192 VT = ST->getMemoryVT();
1193 Ptr = ST->getBasePtr();
1194 // We can not store to program memory.
1196 return false;
1197 // Since the high byte need to be stored first, we can not emit
1198 // i16 post increment store like:
1199 // st X+, r24
1200 // st X+, r25
1201 if (VT == MVT::i16 && !Subtarget.hasLowByteFirst())
1202 return false;
1203 } else {
1204 return false;
1205 }
1206
1207 if (VT != MVT::i8 && VT != MVT::i16) {
1208 return false;
1209 }
1210
1211 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) {
1212 return false;
1213 }
1214
1215 if (const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
1216 int RHSC = RHS->getSExtValue();
1217 if (Op->getOpcode() == ISD::SUB)
1218 RHSC = -RHSC;
1219 if ((VT == MVT::i16 && RHSC != 2) || (VT == MVT::i8 && RHSC != 1)) {
1220 return false;
1221 }
1222
1223 // FIXME: We temporarily disable post increment load from program memory,
1224 // due to bug https://github.com/llvm/llvm-project/issues/59914.
1225 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
1227 return false;
1228
1229 Base = Op->getOperand(0);
1230
1231 // Post-indexing updates the base, so it's not a valid transform
1232 // if that's not the same as the load's pointer.
1233 if (Ptr != Base)
1234 return false;
1235
1236 Offset = DAG.getConstant(RHSC, DL, MVT::i8);
1237 AM = ISD::POST_INC;
1238
1239 return true;
1240 }
1241
1242 return false;
1243}
1244
1246 const GlobalAddressSDNode *GA) const {
1247 return true;
1248}
1249
1250//===----------------------------------------------------------------------===//
1251// Formal Arguments Calling Convention Implementation
1252//===----------------------------------------------------------------------===//
1253
1254#define GET_CALLING_CONV_IMPL
1255#include "AVRGenCallingConv.inc"
1256
1257/// Registers for calling conventions, ordered in reverse as required by ABI.
1258/// Both arrays must be of the same length.
1259static const MCPhysReg RegList8AVR[] = {
1260 AVR::R25, AVR::R24, AVR::R23, AVR::R22, AVR::R21, AVR::R20,
1261 AVR::R19, AVR::R18, AVR::R17, AVR::R16, AVR::R15, AVR::R14,
1262 AVR::R13, AVR::R12, AVR::R11, AVR::R10, AVR::R9, AVR::R8};
1263static const MCPhysReg RegList8Tiny[] = {AVR::R25, AVR::R24, AVR::R23,
1264 AVR::R22, AVR::R21, AVR::R20};
1265static const MCPhysReg RegList16AVR[] = {
1266 AVR::R26R25, AVR::R25R24, AVR::R24R23, AVR::R23R22, AVR::R22R21,
1267 AVR::R21R20, AVR::R20R19, AVR::R19R18, AVR::R18R17, AVR::R17R16,
1268 AVR::R16R15, AVR::R15R14, AVR::R14R13, AVR::R13R12, AVR::R12R11,
1269 AVR::R11R10, AVR::R10R9, AVR::R9R8};
1270static const MCPhysReg RegList16Tiny[] = {AVR::R26R25, AVR::R25R24,
1271 AVR::R24R23, AVR::R23R22,
1272 AVR::R22R21, AVR::R21R20};
1273
1274static_assert(std::size(RegList8AVR) == std::size(RegList16AVR),
1275 "8-bit and 16-bit register arrays must be of equal length");
1276static_assert(std::size(RegList8Tiny) == std::size(RegList16Tiny),
1277 "8-bit and 16-bit register arrays must be of equal length");
1278
1279/// Analyze incoming and outgoing function arguments. We need custom C++ code
1280/// to handle special constraints in the ABI.
1281/// In addition, all pieces of a certain argument have to be passed either
1282/// using registers or the stack but never mixing both.
1283template <typename ArgT>
1285 const Function *F, const DataLayout *TD,
1286 const SmallVectorImpl<ArgT> &Args,
1288 CCState &CCInfo, bool Tiny) {
1289 // Choose the proper register list for argument passing according to the ABI.
1290 ArrayRef<MCPhysReg> RegList8;
1291 ArrayRef<MCPhysReg> RegList16;
1292 if (Tiny) {
1293 RegList8 = ArrayRef(RegList8Tiny);
1294 RegList16 = ArrayRef(RegList16Tiny);
1295 } else {
1296 RegList8 = ArrayRef(RegList8AVR);
1297 RegList16 = ArrayRef(RegList16AVR);
1298 }
1299
1300 unsigned NumArgs = Args.size();
1301 // This is the index of the last used register, in RegList*.
1302 // -1 means R26 (R26 is never actually used in CC).
1303 int RegLastIdx = -1;
1304 // Once a value is passed to the stack it will always be used
1305 bool UseStack = false;
1306 for (unsigned i = 0; i != NumArgs;) {
1307 MVT VT = Args[i].VT;
1308 // We have to count the number of bytes for each function argument, that is
1309 // those Args with the same OrigArgIndex. This is important in case the
1310 // function takes an aggregate type.
1311 // Current argument will be between [i..j).
1312 unsigned ArgIndex = Args[i].OrigArgIndex;
1313 unsigned TotalBytes = VT.getStoreSize();
1314 unsigned j = i + 1;
1315 for (; j != NumArgs; ++j) {
1316 if (Args[j].OrigArgIndex != ArgIndex)
1317 break;
1318 TotalBytes += Args[j].VT.getStoreSize();
1319 }
1320 // Round up to even number of bytes.
1321 TotalBytes = alignTo(TotalBytes, 2);
1322 // Skip zero sized arguments
1323 if (TotalBytes == 0)
1324 continue;
1325 // The index of the first register to be used
1326 unsigned RegIdx = RegLastIdx + TotalBytes;
1327 RegLastIdx = RegIdx;
1328 // If there are not enough registers, use the stack
1329 if (RegIdx >= RegList8.size()) {
1330 UseStack = true;
1331 }
1332 for (; i != j; ++i) {
1333 MVT VT = Args[i].VT;
1334
1335 if (UseStack) {
1336 auto evt = EVT(VT).getTypeForEVT(CCInfo.getContext());
1337 unsigned Offset = CCInfo.AllocateStack(TD->getTypeAllocSize(evt),
1338 TD->getABITypeAlign(evt));
1339 CCInfo.addLoc(
1341 } else {
1342 unsigned Reg;
1343 if (VT == MVT::i8) {
1344 Reg = CCInfo.AllocateReg(RegList8[RegIdx]);
1345 } else if (VT == MVT::i16) {
1346 Reg = CCInfo.AllocateReg(RegList16[RegIdx]);
1347 } else {
1349 "calling convention can only manage i8 and i16 types");
1350 }
1351 assert(Reg && "register not available in calling convention");
1352 CCInfo.addLoc(CCValAssign::getReg(i, VT, Reg, VT, CCValAssign::Full));
1353 // Registers inside a particular argument are sorted in increasing order
1354 // (remember the array is reversed).
1355 RegIdx -= VT.getStoreSize();
1356 }
1357 }
1358 }
1359}
1360
1361/// Count the total number of bytes needed to pass or return these arguments.
1362template <typename ArgT>
1363static unsigned
1365 unsigned TotalBytes = 0;
1366
1367 for (const ArgT &Arg : Args) {
1368 TotalBytes += Arg.VT.getStoreSize();
1369 }
1370 return TotalBytes;
1371}
1372
1373/// Analyze incoming and outgoing value of returning from a function.
1374/// The algorithm is similar to analyzeArguments, but there can only be
1375/// one value, possibly an aggregate, and it is limited to 8 bytes.
1376template <typename ArgT>
1378 CCState &CCInfo, bool Tiny) {
1379 unsigned NumArgs = Args.size();
1380 unsigned TotalBytes = getTotalArgumentsSizeInBytes(Args);
1381 // CanLowerReturn() guarantees this assertion.
1382 if (Tiny)
1383 assert(TotalBytes <= 4 &&
1384 "return values greater than 4 bytes cannot be lowered on AVRTiny");
1385 else
1386 assert(TotalBytes <= 8 &&
1387 "return values greater than 8 bytes cannot be lowered on AVR");
1388
1389 // Choose the proper register list for argument passing according to the ABI.
1390 ArrayRef<MCPhysReg> RegList8;
1391 ArrayRef<MCPhysReg> RegList16;
1392 if (Tiny) {
1393 RegList8 = ArrayRef(RegList8Tiny);
1394 RegList16 = ArrayRef(RegList16Tiny);
1395 } else {
1396 RegList8 = ArrayRef(RegList8AVR);
1397 RegList16 = ArrayRef(RegList16AVR);
1398 }
1399
1400 // GCC-ABI says that the size is rounded up to the next even number,
1401 // but actually once it is more than 4 it will always round up to 8.
1402 if (TotalBytes > 4) {
1403 TotalBytes = 8;
1404 } else {
1405 TotalBytes = alignTo(TotalBytes, 2);
1406 }
1407
1408 // The index of the first register to use.
1409 int RegIdx = TotalBytes - 1;
1410 for (unsigned i = 0; i != NumArgs; ++i) {
1411 MVT VT = Args[i].VT;
1412 unsigned Reg;
1413 if (VT == MVT::i8) {
1414 Reg = CCInfo.AllocateReg(RegList8[RegIdx]);
1415 } else if (VT == MVT::i16) {
1416 Reg = CCInfo.AllocateReg(RegList16[RegIdx]);
1417 } else {
1418 llvm_unreachable("calling convention can only manage i8 and i16 types");
1419 }
1420 assert(Reg && "register not available in calling convention");
1421 CCInfo.addLoc(CCValAssign::getReg(i, VT, Reg, VT, CCValAssign::Full));
1422 // Registers sort in increasing order
1423 RegIdx -= VT.getStoreSize();
1424 }
1425}
1426
1427SDValue AVRTargetLowering::LowerFormalArguments(
1428 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1429 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1430 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1431 MachineFunction &MF = DAG.getMachineFunction();
1432 MachineFrameInfo &MFI = MF.getFrameInfo();
1433 auto DL = DAG.getDataLayout();
1434
1435 // Assign locations to all of the incoming arguments.
1437 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1438 *DAG.getContext());
1439
1440 // Variadic functions do not need all the analysis below.
1441 if (isVarArg) {
1442 CCInfo.AnalyzeFormalArguments(Ins, ArgCC_AVR_Vararg);
1443 } else {
1444 analyzeArguments(nullptr, &MF.getFunction(), &DL, Ins, ArgLocs, CCInfo,
1445 Subtarget.hasTinyEncoding());
1446 }
1447
1448 SDValue ArgValue;
1449 for (CCValAssign &VA : ArgLocs) {
1450
1451 // Arguments stored on registers.
1452 if (VA.isRegLoc()) {
1453 EVT RegVT = VA.getLocVT();
1454 const TargetRegisterClass *RC;
1455 if (RegVT == MVT::i8) {
1456 RC = &AVR::GPR8RegClass;
1457 } else if (RegVT == MVT::i16) {
1458 RC = &AVR::DREGSRegClass;
1459 } else {
1460 llvm_unreachable("Unknown argument type!");
1461 }
1462
1463 Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
1464 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1465
1466 // :NOTE: Clang should not promote any i8 into i16 but for safety the
1467 // following code will handle zexts or sexts generated by other
1468 // front ends. Otherwise:
1469 // If this is an 8 bit value, it is really passed promoted
1470 // to 16 bits. Insert an assert[sz]ext to capture this, then
1471 // truncate to the right size.
1472 switch (VA.getLocInfo()) {
1473 default:
1474 llvm_unreachable("Unknown loc info!");
1475 case CCValAssign::Full:
1476 break;
1477 case CCValAssign::BCvt:
1478 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1479 break;
1480 case CCValAssign::SExt:
1481 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1482 DAG.getValueType(VA.getValVT()));
1483 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1484 break;
1485 case CCValAssign::ZExt:
1486 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1487 DAG.getValueType(VA.getValVT()));
1488 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1489 break;
1490 }
1491
1492 InVals.push_back(ArgValue);
1493 } else {
1494 // Only arguments passed on the stack should make it here.
1495 assert(VA.isMemLoc());
1496
1497 EVT LocVT = VA.getLocVT();
1498
1499 // Create the frame index object for this incoming parameter.
1500 int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
1501 VA.getLocMemOffset(), true);
1502
1503 // Create the SelectionDAG nodes corresponding to a load
1504 // from this parameter.
1505 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DL));
1506 InVals.push_back(DAG.getLoad(LocVT, dl, Chain, FIN,
1508 }
1509 }
1510
1511 // If the function takes variable number of arguments, make a frame index for
1512 // the start of the first vararg value... for expansion of llvm.va_start.
1513 if (isVarArg) {
1514 unsigned StackSize = CCInfo.getStackSize();
1515 AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>();
1516
1517 AFI->setVarArgsFrameIndex(MFI.CreateFixedObject(2, StackSize, true));
1518 }
1519
1520 return Chain;
1521}
1522
1523//===----------------------------------------------------------------------===//
1524// Call Calling Convention Implementation
1525//===----------------------------------------------------------------------===//
1526
1527SDValue AVRTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1528 SmallVectorImpl<SDValue> &InVals) const {
1529 SelectionDAG &DAG = CLI.DAG;
1530 SDLoc &DL = CLI.DL;
1531 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1532 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1533 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1534 SDValue Chain = CLI.Chain;
1535 SDValue Callee = CLI.Callee;
1536 bool &isTailCall = CLI.IsTailCall;
1537 CallingConv::ID CallConv = CLI.CallConv;
1538 bool isVarArg = CLI.IsVarArg;
1539
1540 MachineFunction &MF = DAG.getMachineFunction();
1541
1542 // AVR does not yet support tail call optimization.
1543 isTailCall = false;
1544
1545 // Analyze operands of the call, assigning locations to each operand.
1547 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1548 *DAG.getContext());
1549
1550 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1551 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1552 // node so that legalize doesn't hack it.
1553 const Function *F = nullptr;
1554 if (const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1555 const GlobalValue *GV = G->getGlobal();
1556 if (isa<Function>(GV))
1557 F = cast<Function>(GV);
1558 Callee =
1559 DAG.getTargetGlobalAddress(GV, DL, getPointerTy(DAG.getDataLayout()));
1560 } else if (const ExternalSymbolSDNode *ES =
1562 Callee = DAG.getTargetExternalSymbol(ES->getSymbol(),
1563 getPointerTy(DAG.getDataLayout()));
1564 }
1565
1566 // Variadic functions do not need all the analysis below.
1567 if (isVarArg) {
1568 CCInfo.AnalyzeCallOperands(Outs, ArgCC_AVR_Vararg);
1569 } else {
1570 analyzeArguments(&CLI, F, &DAG.getDataLayout(), Outs, ArgLocs, CCInfo,
1571 Subtarget.hasTinyEncoding());
1572 }
1573
1574 // Get a count of how many bytes are to be pushed on the stack.
1575 unsigned NumBytes = CCInfo.getStackSize();
1576
1577 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
1578
1580
1581 // First, walk the register assignments, inserting copies.
1582 unsigned AI, AE;
1583 bool HasStackArgs = false;
1584 for (AI = 0, AE = ArgLocs.size(); AI != AE; ++AI) {
1585 CCValAssign &VA = ArgLocs[AI];
1586 EVT RegVT = VA.getLocVT();
1587 SDValue Arg = OutVals[AI];
1588
1589 // Promote the value if needed. With Clang this should not happen.
1590 switch (VA.getLocInfo()) {
1591 default:
1592 llvm_unreachable("Unknown loc info!");
1593 case CCValAssign::Full:
1594 break;
1595 case CCValAssign::SExt:
1596 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, RegVT, Arg);
1597 break;
1598 case CCValAssign::ZExt:
1599 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, RegVT, Arg);
1600 break;
1601 case CCValAssign::AExt:
1602 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, RegVT, Arg);
1603 break;
1604 case CCValAssign::BCvt:
1605 Arg = DAG.getNode(ISD::BITCAST, DL, RegVT, Arg);
1606 break;
1607 }
1608
1609 // Stop when we encounter a stack argument, we need to process them
1610 // in reverse order in the loop below.
1611 if (VA.isMemLoc()) {
1612 HasStackArgs = true;
1613 break;
1614 }
1615
1616 // Arguments that can be passed on registers must be kept in the RegsToPass
1617 // vector.
1618 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1619 }
1620
1621 // Second, stack arguments have to walked.
1622 // Previously this code created chained stores but those chained stores appear
1623 // to be unchained in the legalization phase. Therefore, do not attempt to
1624 // chain them here. In fact, chaining them here somehow causes the first and
1625 // second store to be reversed which is the exact opposite of the intended
1626 // effect.
1627 if (HasStackArgs) {
1628 SmallVector<SDValue, 8> MemOpChains;
1629 for (; AI != AE; AI++) {
1630 CCValAssign &VA = ArgLocs[AI];
1631 SDValue Arg = OutVals[AI];
1632
1633 assert(VA.isMemLoc());
1634
1635 // SP points to one stack slot further so add one to adjust it.
1636 SDValue PtrOff = DAG.getNode(
1637 ISD::ADD, DL, getPointerTy(DAG.getDataLayout()),
1638 DAG.getRegister(AVR::SP, getPointerTy(DAG.getDataLayout())),
1639 DAG.getIntPtrConstant(VA.getLocMemOffset() + 1, DL));
1640
1641 MemOpChains.push_back(
1642 DAG.getStore(Chain, DL, Arg, PtrOff,
1643 MachinePointerInfo::getStack(MF, VA.getLocMemOffset())));
1644 }
1645
1646 if (!MemOpChains.empty())
1647 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1648 }
1649
1650 // Build a sequence of copy-to-reg nodes chained together with token chain and
1651 // flag operands which copy the outgoing args into registers. The InGlue in
1652 // necessary since all emited instructions must be stuck together.
1653 SDValue InGlue;
1654 for (auto Reg : RegsToPass) {
1655 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, InGlue);
1656 InGlue = Chain.getValue(1);
1657 }
1658
1659 // Returns a chain & a flag for retval copy to use.
1660 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1662 Ops.push_back(Chain);
1663 Ops.push_back(Callee);
1664
1665 // Add argument registers to the end of the list so that they are known live
1666 // into the call.
1667 for (auto Reg : RegsToPass) {
1668 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
1669 }
1670
1671 // The zero register (usually R1) must be passed as an implicit register so
1672 // that this register is correctly zeroed in interrupts.
1673 Ops.push_back(DAG.getRegister(Subtarget.getZeroRegister(), MVT::i8));
1674
1675 // Add a register mask operand representing the call-preserved registers.
1676 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1677 const uint32_t *Mask =
1678 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
1679 assert(Mask && "Missing call preserved mask for calling convention");
1680 Ops.push_back(DAG.getRegisterMask(Mask));
1681
1682 if (InGlue.getNode()) {
1683 Ops.push_back(InGlue);
1684 }
1685
1686 Chain = DAG.getNode(AVRISD::CALL, DL, NodeTys, Ops);
1687 InGlue = Chain.getValue(1);
1688
1689 // Create the CALLSEQ_END node.
1690 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, InGlue, DL);
1691
1692 if (!Ins.empty()) {
1693 InGlue = Chain.getValue(1);
1694 }
1695
1696 // Handle result values, copying them out of physregs into vregs that we
1697 // return.
1698 return LowerCallResult(Chain, InGlue, CallConv, isVarArg, Ins, DL, DAG,
1699 InVals);
1700}
1701
1702/// Lower the result values of a call into the
1703/// appropriate copies out of appropriate physical registers.
1704///
1705SDValue AVRTargetLowering::LowerCallResult(
1706 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool isVarArg,
1707 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1708 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1709
1710 // Assign locations to each value returned by this call.
1712 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1713 *DAG.getContext());
1714
1715 // Handle runtime calling convs.
1716 if (CallConv == CallingConv::AVR_BUILTIN) {
1717 CCInfo.AnalyzeCallResult(Ins, RetCC_AVR_BUILTIN);
1718 } else {
1719 analyzeReturnValues(Ins, CCInfo, Subtarget.hasTinyEncoding());
1720 }
1721
1722 // Copy all of the result registers out of their specified physreg.
1723 for (CCValAssign const &RVLoc : RVLocs) {
1724 Chain = DAG.getCopyFromReg(Chain, dl, RVLoc.getLocReg(), RVLoc.getValVT(),
1725 InGlue)
1726 .getValue(1);
1727 InGlue = Chain.getValue(2);
1728 InVals.push_back(Chain.getValue(0));
1729 }
1730
1731 return Chain;
1732}
1733
1734//===----------------------------------------------------------------------===//
1735// Return Value Calling Convention Implementation
1736//===----------------------------------------------------------------------===//
1737
1738bool AVRTargetLowering::CanLowerReturn(
1739 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
1741 const Type *RetTy) const {
1742 if (CallConv == CallingConv::AVR_BUILTIN) {
1744 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1745 return CCInfo.CheckReturn(Outs, RetCC_AVR_BUILTIN);
1746 }
1747
1748 unsigned TotalBytes = getTotalArgumentsSizeInBytes(Outs);
1749 return TotalBytes <= (unsigned)(Subtarget.hasTinyEncoding() ? 4 : 8);
1750}
1751
1752SDValue
1753AVRTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1754 bool isVarArg,
1756 const SmallVectorImpl<SDValue> &OutVals,
1757 const SDLoc &dl, SelectionDAG &DAG) const {
1758 // CCValAssign - represent the assignment of the return value to locations.
1760
1761 // CCState - Info about the registers and stack slot.
1762 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1763 *DAG.getContext());
1764
1765 MachineFunction &MF = DAG.getMachineFunction();
1766
1767 // Analyze return values.
1768 if (CallConv == CallingConv::AVR_BUILTIN) {
1769 CCInfo.AnalyzeReturn(Outs, RetCC_AVR_BUILTIN);
1770 } else {
1771 analyzeReturnValues(Outs, CCInfo, Subtarget.hasTinyEncoding());
1772 }
1773
1774 SDValue Glue;
1775 SmallVector<SDValue, 4> RetOps(1, Chain);
1776 // Copy the result values into the output registers.
1777 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1778 CCValAssign &VA = RVLocs[i];
1779 assert(VA.isRegLoc() && "Can only return in registers!");
1780
1781 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Glue);
1782
1783 // Guarantee that all emitted copies are stuck together with flags.
1784 Glue = Chain.getValue(1);
1785 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1786 }
1787
1788 // Don't emit the ret/reti instruction when the naked attribute is present in
1789 // the function being compiled.
1790 if (MF.getFunction().getAttributes().hasFnAttr(Attribute::Naked)) {
1791 return Chain;
1792 }
1793
1794 const AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>();
1795
1796 if (!AFI->isInterruptOrSignalHandler()) {
1797 // The return instruction has an implicit zero register operand: it must
1798 // contain zero on return.
1799 // This is not needed in interrupts however, where the zero register is
1800 // handled specially (only pushed/popped when needed).
1801 RetOps.push_back(DAG.getRegister(Subtarget.getZeroRegister(), MVT::i8));
1802 }
1803
1804 unsigned RetOpc =
1805 AFI->isInterruptOrSignalHandler() ? AVRISD::RETI_GLUE : AVRISD::RET_GLUE;
1806
1807 RetOps[0] = Chain; // Update chain.
1808
1809 if (Glue.getNode()) {
1810 RetOps.push_back(Glue);
1811 }
1812
1813 return DAG.getNode(RetOpc, dl, MVT::Other, RetOps);
1814}
1815
1816//===----------------------------------------------------------------------===//
1817// Custom Inserters
1818//===----------------------------------------------------------------------===//
1819
1820MachineBasicBlock *AVRTargetLowering::insertShift(MachineInstr &MI,
1822 bool Tiny) const {
1823 unsigned Opc;
1824 const TargetRegisterClass *RC;
1825 bool HasRepeatedOperand = false;
1826 MachineFunction *F = BB->getParent();
1827 MachineRegisterInfo &RI = F->getRegInfo();
1828 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1829 DebugLoc dl = MI.getDebugLoc();
1830
1831 switch (MI.getOpcode()) {
1832 default:
1833 llvm_unreachable("Invalid shift opcode!");
1834 case AVR::Lsl8:
1835 Opc = AVR::ADDRdRr; // LSL is an alias of ADD Rd, Rd
1836 RC = &AVR::GPR8RegClass;
1837 HasRepeatedOperand = true;
1838 break;
1839 case AVR::Lsl16:
1840 Opc = AVR::LSLWRd;
1841 RC = &AVR::DREGSRegClass;
1842 break;
1843 case AVR::Asr8:
1844 Opc = AVR::ASRRd;
1845 RC = &AVR::GPR8RegClass;
1846 break;
1847 case AVR::Asr16:
1848 Opc = AVR::ASRWRd;
1849 RC = &AVR::DREGSRegClass;
1850 break;
1851 case AVR::Lsr8:
1852 Opc = AVR::LSRRd;
1853 RC = &AVR::GPR8RegClass;
1854 break;
1855 case AVR::Lsr16:
1856 Opc = AVR::LSRWRd;
1857 RC = &AVR::DREGSRegClass;
1858 break;
1859 case AVR::Rol8:
1860 Opc = Tiny ? AVR::ROLBRdR17 : AVR::ROLBRdR1;
1861 RC = &AVR::GPR8RegClass;
1862 break;
1863 case AVR::Rol16:
1864 Opc = AVR::ROLWRd;
1865 RC = &AVR::DREGSRegClass;
1866 break;
1867 case AVR::Ror8:
1868 Opc = AVR::RORBRd;
1869 RC = &AVR::GPR8RegClass;
1870 break;
1871 case AVR::Ror16:
1872 Opc = AVR::RORWRd;
1873 RC = &AVR::DREGSRegClass;
1874 break;
1875 }
1876
1877 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1878
1880 for (I = BB->getIterator(); I != F->end() && &(*I) != BB; ++I)
1881 ;
1882 if (I != F->end())
1883 ++I;
1884
1885 // Create loop block.
1886 MachineBasicBlock *LoopBB = F->CreateMachineBasicBlock(LLVM_BB);
1887 MachineBasicBlock *CheckBB = F->CreateMachineBasicBlock(LLVM_BB);
1888 MachineBasicBlock *RemBB = F->CreateMachineBasicBlock(LLVM_BB);
1889
1890 F->insert(I, LoopBB);
1891 F->insert(I, CheckBB);
1892 F->insert(I, RemBB);
1893
1894 // Update machine-CFG edges by transferring all successors of the current
1895 // block to the block containing instructions after shift.
1896 RemBB->splice(RemBB->begin(), BB, std::next(MachineBasicBlock::iterator(MI)),
1897 BB->end());
1898 RemBB->transferSuccessorsAndUpdatePHIs(BB);
1899
1900 // Add edges BB => LoopBB => CheckBB => RemBB, CheckBB => LoopBB.
1901 BB->addSuccessor(CheckBB);
1902 LoopBB->addSuccessor(CheckBB);
1903 CheckBB->addSuccessor(LoopBB);
1904 CheckBB->addSuccessor(RemBB);
1905
1906 Register ShiftAmtReg = RI.createVirtualRegister(&AVR::GPR8RegClass);
1907 Register ShiftAmtReg2 = RI.createVirtualRegister(&AVR::GPR8RegClass);
1908 Register ShiftReg = RI.createVirtualRegister(RC);
1909 Register ShiftReg2 = RI.createVirtualRegister(RC);
1910 Register ShiftAmtSrcReg = MI.getOperand(2).getReg();
1911 Register SrcReg = MI.getOperand(1).getReg();
1912 Register DstReg = MI.getOperand(0).getReg();
1913
1914 // BB:
1915 // rjmp CheckBB
1916 BuildMI(BB, dl, TII.get(AVR::RJMPk)).addMBB(CheckBB);
1917
1918 // LoopBB:
1919 // ShiftReg2 = shift ShiftReg
1920 auto ShiftMI = BuildMI(LoopBB, dl, TII.get(Opc), ShiftReg2).addReg(ShiftReg);
1921 if (HasRepeatedOperand)
1922 ShiftMI.addReg(ShiftReg);
1923
1924 // CheckBB:
1925 // ShiftReg = phi [%SrcReg, BB], [%ShiftReg2, LoopBB]
1926 // ShiftAmt = phi [%N, BB], [%ShiftAmt2, LoopBB]
1927 // DestReg = phi [%SrcReg, BB], [%ShiftReg, LoopBB]
1928 // ShiftAmt2 = ShiftAmt - 1;
1929 // if (ShiftAmt2 >= 0) goto LoopBB;
1930 BuildMI(CheckBB, dl, TII.get(AVR::PHI), ShiftReg)
1931 .addReg(SrcReg)
1932 .addMBB(BB)
1933 .addReg(ShiftReg2)
1934 .addMBB(LoopBB);
1935 BuildMI(CheckBB, dl, TII.get(AVR::PHI), ShiftAmtReg)
1936 .addReg(ShiftAmtSrcReg)
1937 .addMBB(BB)
1938 .addReg(ShiftAmtReg2)
1939 .addMBB(LoopBB);
1940 BuildMI(CheckBB, dl, TII.get(AVR::PHI), DstReg)
1941 .addReg(SrcReg)
1942 .addMBB(BB)
1943 .addReg(ShiftReg2)
1944 .addMBB(LoopBB);
1945
1946 BuildMI(CheckBB, dl, TII.get(AVR::DECRd), ShiftAmtReg2).addReg(ShiftAmtReg);
1947 BuildMI(CheckBB, dl, TII.get(AVR::BRPLk)).addMBB(LoopBB);
1948
1949 MI.eraseFromParent(); // The pseudo instruction is gone now.
1950 return RemBB;
1951}
1952
1953// Do a multibyte AVR shift. Insert shift instructions and put the output
1954// registers in the Regs array.
1955// Because AVR does not have a normal shift instruction (only a single bit shift
1956// instruction), we have to emulate this behavior with other instructions.
1957// It first tries large steps (moving registers around) and then smaller steps
1958// like single bit shifts.
1959// Large shifts actually reduce the number of shifted registers, so the below
1960// algorithms have to work independently of the number of registers that are
1961// shifted.
1962// For more information and background, see this blogpost:
1963// https://aykevl.nl/2021/02/avr-bitshift
1965 MutableArrayRef<std::pair<Register, int>> Regs,
1966 ISD::NodeType Opc, int64_t ShiftAmt) {
1968 const AVRSubtarget &STI = BB->getParent()->getSubtarget<AVRSubtarget>();
1970 const DebugLoc &dl = MI.getDebugLoc();
1971
1972 const bool ShiftLeft = Opc == ISD::SHL;
1973 const bool ArithmeticShift = Opc == ISD::SRA;
1974
1975 // Zero a register, for use in later operations.
1976 Register ZeroReg = MRI.createVirtualRegister(&AVR::GPR8RegClass);
1977 BuildMI(*BB, MI, dl, TII.get(AVR::COPY), ZeroReg)
1978 .addReg(STI.getZeroRegister());
1979
1980 // Do a shift modulo 6 or 7. This is a bit more complicated than most shifts
1981 // and is hard to compose with the rest, so these are special cased.
1982 // The basic idea is to shift one or two bits in the opposite direction and
1983 // then move registers around to get the correct end result.
1984 if (ShiftLeft && (ShiftAmt % 8) >= 6) {
1985 // Left shift modulo 6 or 7.
1986
1987 // Create a slice of the registers we're going to modify, to ease working
1988 // with them.
1989 size_t ShiftRegsOffset = ShiftAmt / 8;
1990 size_t ShiftRegsSize = Regs.size() - ShiftRegsOffset;
1992 Regs.slice(ShiftRegsOffset, ShiftRegsSize);
1993
1994 // Shift one to the right, keeping the least significant bit as the carry
1995 // bit.
1996 insertMultibyteShift(MI, BB, ShiftRegs, ISD::SRL, 1);
1997
1998 // Rotate the least significant bit from the carry bit into a new register
1999 // (that starts out zero).
2000 Register LowByte = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2001 BuildMI(*BB, MI, dl, TII.get(AVR::RORRd), LowByte).addReg(ZeroReg);
2002
2003 // Shift one more to the right if this is a modulo-6 shift.
2004 if (ShiftAmt % 8 == 6) {
2005 insertMultibyteShift(MI, BB, ShiftRegs, ISD::SRL, 1);
2006 Register NewLowByte = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2007 BuildMI(*BB, MI, dl, TII.get(AVR::RORRd), NewLowByte).addReg(LowByte);
2008 LowByte = NewLowByte;
2009 }
2010
2011 // Move all registers to the left, zeroing the bottom registers as needed.
2012 for (size_t I = 0; I < Regs.size(); I++) {
2013 int ShiftRegsIdx = I + 1;
2014 if (ShiftRegsIdx < (int)ShiftRegs.size()) {
2015 Regs[I] = ShiftRegs[ShiftRegsIdx];
2016 } else if (ShiftRegsIdx == (int)ShiftRegs.size()) {
2017 Regs[I] = std::pair(LowByte, 0);
2018 } else {
2019 Regs[I] = std::pair(ZeroReg, 0);
2020 }
2021 }
2022
2023 return;
2024 }
2025
2026 // Right shift modulo 6 or 7.
2027 if (!ShiftLeft && (ShiftAmt % 8) >= 6) {
2028 // Create a view on the registers we're going to modify, to ease working
2029 // with them.
2030 size_t ShiftRegsSize = Regs.size() - (ShiftAmt / 8);
2032 Regs.slice(0, ShiftRegsSize);
2033
2034 // Shift one to the left.
2035 insertMultibyteShift(MI, BB, ShiftRegs, ISD::SHL, 1);
2036
2037 // Sign or zero extend the most significant register into a new register.
2038 // The HighByte is the byte that still has one (or two) bits from the
2039 // original value. The ExtByte is purely a zero/sign extend byte (all bits
2040 // are either 0 or 1).
2041 Register HighByte = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2042 Register ExtByte = 0;
2043 if (ArithmeticShift) {
2044 // Sign-extend bit that was shifted out last.
2045 BuildMI(*BB, MI, dl, TII.get(AVR::SBCRdRr), HighByte)
2046 .addReg(HighByte, RegState::Undef)
2047 .addReg(HighByte, RegState::Undef);
2048 ExtByte = HighByte;
2049 // The highest bit of the original value is the same as the zero-extend
2050 // byte, so HighByte and ExtByte are the same.
2051 } else {
2052 // Use the zero register for zero extending.
2053 ExtByte = ZeroReg;
2054 // Rotate most significant bit into a new register (that starts out zero).
2055 BuildMI(*BB, MI, dl, TII.get(AVR::ADCRdRr), HighByte)
2056 .addReg(ExtByte)
2057 .addReg(ExtByte);
2058 }
2059
2060 // Shift one more to the left for modulo 6 shifts.
2061 if (ShiftAmt % 8 == 6) {
2062 insertMultibyteShift(MI, BB, ShiftRegs, ISD::SHL, 1);
2063 // Shift the topmost bit into the HighByte.
2064 Register NewExt = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2065 BuildMI(*BB, MI, dl, TII.get(AVR::ADCRdRr), NewExt)
2066 .addReg(HighByte)
2067 .addReg(HighByte);
2068 HighByte = NewExt;
2069 }
2070
2071 // Move all to the right, while sign or zero extending.
2072 for (int I = Regs.size() - 1; I >= 0; I--) {
2073 int ShiftRegsIdx = I - (Regs.size() - ShiftRegs.size()) - 1;
2074 if (ShiftRegsIdx >= 0) {
2075 Regs[I] = ShiftRegs[ShiftRegsIdx];
2076 } else if (ShiftRegsIdx == -1) {
2077 Regs[I] = std::pair(HighByte, 0);
2078 } else {
2079 Regs[I] = std::pair(ExtByte, 0);
2080 }
2081 }
2082
2083 return;
2084 }
2085
2086 // For shift amounts of at least one register, simply rename the registers and
2087 // zero the bottom registers.
2088 while (ShiftLeft && ShiftAmt >= 8) {
2089 // Move all registers one to the left.
2090 for (size_t I = 0; I < Regs.size() - 1; I++) {
2091 Regs[I] = Regs[I + 1];
2092 }
2093
2094 // Zero the least significant register.
2095 Regs[Regs.size() - 1] = std::pair(ZeroReg, 0);
2096
2097 // Continue shifts with the leftover registers.
2098 Regs = Regs.drop_back(1);
2099
2100 ShiftAmt -= 8;
2101 }
2102
2103 // And again, the same for right shifts.
2104 Register ShrExtendReg = 0;
2105 if (!ShiftLeft && ShiftAmt >= 8) {
2106 if (ArithmeticShift) {
2107 // Sign extend the most significant register into ShrExtendReg.
2108 ShrExtendReg = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2109 Register Tmp = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2110 BuildMI(*BB, MI, dl, TII.get(AVR::ADDRdRr), Tmp)
2111 .addReg(Regs[0].first, {}, Regs[0].second)
2112 .addReg(Regs[0].first, {}, Regs[0].second);
2113 BuildMI(*BB, MI, dl, TII.get(AVR::SBCRdRr), ShrExtendReg)
2114 .addReg(Tmp)
2115 .addReg(Tmp);
2116 } else {
2117 ShrExtendReg = ZeroReg;
2118 }
2119 for (; ShiftAmt >= 8; ShiftAmt -= 8) {
2120 // Move all registers one to the right.
2121 for (size_t I = Regs.size() - 1; I != 0; I--) {
2122 Regs[I] = Regs[I - 1];
2123 }
2124
2125 // Zero or sign extend the most significant register.
2126 Regs[0] = std::pair(ShrExtendReg, 0);
2127
2128 // Continue shifts with the leftover registers.
2129 Regs = Regs.drop_front(1);
2130 }
2131 }
2132
2133 // The bigger shifts are already handled above.
2134 assert((ShiftAmt < 8) && "Unexpect shift amount");
2135
2136 // Shift by four bits, using a complicated swap/eor/andi/eor sequence.
2137 // It only works for logical shifts because the bits shifted in are all
2138 // zeroes.
2139 // To shift a single byte right, it produces code like this:
2140 // swap r0
2141 // andi r0, 0x0f
2142 // For a two-byte (16-bit) shift, it adds the following instructions to shift
2143 // the upper byte into the lower byte:
2144 // swap r1
2145 // eor r0, r1
2146 // andi r1, 0x0f
2147 // eor r0, r1
2148 // For bigger shifts, it repeats the above sequence. For example, for a 3-byte
2149 // (24-bit) shift it adds:
2150 // swap r2
2151 // eor r1, r2
2152 // andi r2, 0x0f
2153 // eor r1, r2
2154 if (!ArithmeticShift && ShiftAmt >= 4) {
2155 Register Prev = 0;
2156 for (size_t I = 0; I < Regs.size(); I++) {
2157 size_t Idx = ShiftLeft ? I : Regs.size() - I - 1;
2158 Register SwapReg = MRI.createVirtualRegister(&AVR::LD8RegClass);
2159 BuildMI(*BB, MI, dl, TII.get(AVR::SWAPRd), SwapReg)
2160 .addReg(Regs[Idx].first, {}, Regs[Idx].second);
2161 if (I != 0) {
2162 Register R = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2163 BuildMI(*BB, MI, dl, TII.get(AVR::EORRdRr), R)
2164 .addReg(Prev)
2165 .addReg(SwapReg);
2166 Prev = R;
2167 }
2168 Register AndReg = MRI.createVirtualRegister(&AVR::LD8RegClass);
2169 BuildMI(*BB, MI, dl, TII.get(AVR::ANDIRdK), AndReg)
2170 .addReg(SwapReg)
2171 .addImm(ShiftLeft ? 0xf0 : 0x0f);
2172 if (I != 0) {
2173 Register R = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2174 BuildMI(*BB, MI, dl, TII.get(AVR::EORRdRr), R)
2175 .addReg(Prev)
2176 .addReg(AndReg);
2177 size_t PrevIdx = ShiftLeft ? Idx - 1 : Idx + 1;
2178 Regs[PrevIdx] = std::pair(R, 0);
2179 }
2180 Prev = AndReg;
2181 Regs[Idx] = std::pair(AndReg, 0);
2182 }
2183 ShiftAmt -= 4;
2184 }
2185
2186 // Shift by one. This is the fallback that always works, and the shift
2187 // operation that is used for 1, 2, and 3 bit shifts.
2188 while (ShiftLeft && ShiftAmt) {
2189 // Shift one to the left.
2190 for (ssize_t I = Regs.size() - 1; I >= 0; I--) {
2191 Register Out = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2192 Register In = Regs[I].first;
2193 Register InSubreg = Regs[I].second;
2194 if (I == (ssize_t)Regs.size() - 1) { // first iteration
2195 BuildMI(*BB, MI, dl, TII.get(AVR::ADDRdRr), Out)
2196 .addReg(In, {}, InSubreg)
2197 .addReg(In, {}, InSubreg);
2198 } else {
2199 BuildMI(*BB, MI, dl, TII.get(AVR::ADCRdRr), Out)
2200 .addReg(In, {}, InSubreg)
2201 .addReg(In, {}, InSubreg);
2202 }
2203 Regs[I] = std::pair(Out, 0);
2204 }
2205 ShiftAmt--;
2206 }
2207 while (!ShiftLeft && ShiftAmt) {
2208 // Shift one to the right.
2209 for (size_t I = 0; I < Regs.size(); I++) {
2210 Register Out = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2211 Register In = Regs[I].first;
2212 Register InSubreg = Regs[I].second;
2213 if (I == 0) {
2214 unsigned Opc = ArithmeticShift ? AVR::ASRRd : AVR::LSRRd;
2215 BuildMI(*BB, MI, dl, TII.get(Opc), Out).addReg(In, {}, InSubreg);
2216 } else {
2217 BuildMI(*BB, MI, dl, TII.get(AVR::RORRd), Out).addReg(In, {}, InSubreg);
2218 }
2219 Regs[I] = std::pair(Out, 0);
2220 }
2221 ShiftAmt--;
2222 }
2223
2224 if (ShiftAmt != 0) {
2225 llvm_unreachable("don't know how to shift!"); // sanity check
2226 }
2227}
2228
2229// Do a wide (32-bit) shift.
2230MachineBasicBlock *
2231AVRTargetLowering::insertWideShift(MachineInstr &MI,
2232 MachineBasicBlock *BB) const {
2233 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
2234 const DebugLoc &dl = MI.getDebugLoc();
2235
2236 // How much to shift to the right (meaning: a negative number indicates a left
2237 // shift).
2238 int64_t ShiftAmt = MI.getOperand(4).getImm();
2240 switch (MI.getOpcode()) {
2241 case AVR::Lsl32:
2242 Opc = ISD::SHL;
2243 break;
2244 case AVR::Lsr32:
2245 Opc = ISD::SRL;
2246 break;
2247 case AVR::Asr32:
2248 Opc = ISD::SRA;
2249 break;
2250 }
2251
2252 // Read the input registers, with the most significant register at index 0.
2253 std::array<std::pair<Register, int>, 4> Registers = {
2254 std::pair(MI.getOperand(3).getReg(), AVR::sub_hi),
2255 std::pair(MI.getOperand(3).getReg(), AVR::sub_lo),
2256 std::pair(MI.getOperand(2).getReg(), AVR::sub_hi),
2257 std::pair(MI.getOperand(2).getReg(), AVR::sub_lo),
2258 };
2259
2260 // Do the shift. The registers are modified in-place.
2261 insertMultibyteShift(MI, BB, Registers, Opc, ShiftAmt);
2262
2263 // Combine the 8-bit registers into 16-bit register pairs.
2264 // This done either from LSB to MSB or from MSB to LSB, depending on the
2265 // shift. It's an optimization so that the register allocator will use the
2266 // fewest movs possible (which order we use isn't a correctness issue, just an
2267 // optimization issue).
2268 // - lsl prefers starting from the most significant byte (2nd case).
2269 // - lshr prefers starting from the least significant byte (1st case).
2270 // - for ashr it depends on the number of shifted bytes.
2271 // Some shift operations still don't get the most optimal mov sequences even
2272 // with this distinction.
2273 // TODO: Figure out why and try to fix it (but we're
2274 // already equal to or faster than avr-gcc in all cases except ashr 8).
2275 if (Opc != ISD::SHL &&
2276 (Opc != ISD::SRA || (ShiftAmt < 16 || ShiftAmt >= 22))) {
2277 // Use the resulting registers starting with the least significant byte.
2278 BuildMI(*BB, MI, dl, TII.get(AVR::REG_SEQUENCE), MI.getOperand(0).getReg())
2279 .addReg(Registers[3].first, {}, Registers[3].second)
2280 .addImm(AVR::sub_lo)
2281 .addReg(Registers[2].first, {}, Registers[2].second)
2282 .addImm(AVR::sub_hi);
2283 BuildMI(*BB, MI, dl, TII.get(AVR::REG_SEQUENCE), MI.getOperand(1).getReg())
2284 .addReg(Registers[1].first, {}, Registers[1].second)
2285 .addImm(AVR::sub_lo)
2286 .addReg(Registers[0].first, {}, Registers[0].second)
2287 .addImm(AVR::sub_hi);
2288 } else {
2289 // Use the resulting registers starting with the most significant byte.
2290 BuildMI(*BB, MI, dl, TII.get(AVR::REG_SEQUENCE), MI.getOperand(1).getReg())
2291 .addReg(Registers[0].first, {}, Registers[0].second)
2292 .addImm(AVR::sub_hi)
2293 .addReg(Registers[1].first, {}, Registers[1].second)
2294 .addImm(AVR::sub_lo);
2295 BuildMI(*BB, MI, dl, TII.get(AVR::REG_SEQUENCE), MI.getOperand(0).getReg())
2296 .addReg(Registers[2].first, {}, Registers[2].second)
2297 .addImm(AVR::sub_hi)
2298 .addReg(Registers[3].first, {}, Registers[3].second)
2299 .addImm(AVR::sub_lo);
2300 }
2301
2302 // Remove the pseudo instruction.
2303 MI.eraseFromParent();
2304 return BB;
2305}
2306
2308 if (I->getOpcode() == AVR::COPY) {
2309 Register SrcReg = I->getOperand(1).getReg();
2310 return (SrcReg == AVR::R0 || SrcReg == AVR::R1);
2311 }
2312
2313 return false;
2314}
2315
2316// The mul instructions wreak havock on our zero_reg R1. We need to clear it
2317// after the result has been evacuated. This is probably not the best way to do
2318// it, but it works for now.
2319MachineBasicBlock *AVRTargetLowering::insertMul(MachineInstr &MI,
2320 MachineBasicBlock *BB) const {
2321 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
2323 ++I; // in any case insert *after* the mul instruction
2324 if (isCopyMulResult(I))
2325 ++I;
2326 if (isCopyMulResult(I))
2327 ++I;
2328 BuildMI(*BB, I, MI.getDebugLoc(), TII.get(AVR::EORRdRr), AVR::R1)
2329 .addReg(AVR::R1)
2330 .addReg(AVR::R1);
2331 return BB;
2332}
2333
2334// Insert a read from the zero register.
2336AVRTargetLowering::insertCopyZero(MachineInstr &MI,
2337 MachineBasicBlock *BB) const {
2338 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
2340 BuildMI(*BB, I, MI.getDebugLoc(), TII.get(AVR::COPY))
2341 .add(MI.getOperand(0))
2342 .addReg(Subtarget.getZeroRegister());
2343 MI.eraseFromParent();
2344 return BB;
2345}
2346
2347// Lower atomicrmw operation to disable interrupts, do operation, and restore
2348// interrupts. This works because all AVR microcontrollers are single core.
2349MachineBasicBlock *AVRTargetLowering::insertAtomicArithmeticOp(
2350 MachineInstr &MI, MachineBasicBlock *BB, unsigned Opcode, int Width) const {
2351 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
2352 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
2354 DebugLoc dl = MI.getDebugLoc();
2355
2356 // Example instruction sequence, for an atomic 8-bit add:
2357 // ldi r25, 5
2358 // in r0, SREG
2359 // cli
2360 // ld r24, X
2361 // add r25, r24
2362 // st X, r25
2363 // out SREG, r0
2364
2365 const TargetRegisterClass *RC =
2366 (Width == 8) ? &AVR::GPR8RegClass : &AVR::DREGSNOZRegClass;
2367 unsigned LoadOpcode = (Width == 8) ? AVR::LDRdPtr : AVR::LDWRdPtr;
2368 unsigned StoreOpcode = (Width == 8) ? AVR::STPtrRr : AVR::STWPtrRr;
2369
2370 // Disable interrupts.
2371 BuildMI(*BB, I, dl, TII.get(AVR::INRdA), Subtarget.getTmpRegister())
2372 .addImm(Subtarget.getIORegSREG());
2373 BuildMI(*BB, I, dl, TII.get(AVR::BCLRs)).addImm(7);
2374
2375 // Load the original value.
2376 BuildMI(*BB, I, dl, TII.get(LoadOpcode), MI.getOperand(0).getReg())
2377 .add(MI.getOperand(1));
2378
2379 // Do the arithmetic operation.
2380 Register Result = MRI.createVirtualRegister(RC);
2381 BuildMI(*BB, I, dl, TII.get(Opcode), Result)
2382 .addReg(MI.getOperand(0).getReg())
2383 .add(MI.getOperand(2));
2384
2385 // Store the result.
2386 BuildMI(*BB, I, dl, TII.get(StoreOpcode))
2387 .add(MI.getOperand(1))
2388 .addReg(Result);
2389
2390 // Restore interrupts.
2391 BuildMI(*BB, I, dl, TII.get(AVR::OUTARr))
2392 .addImm(Subtarget.getIORegSREG())
2393 .addReg(Subtarget.getTmpRegister());
2394
2395 // Remove the pseudo instruction.
2396 MI.eraseFromParent();
2397 return BB;
2398}
2399
2402 MachineBasicBlock *MBB) const {
2403 int Opc = MI.getOpcode();
2404 const AVRSubtarget &STI = MBB->getParent()->getSubtarget<AVRSubtarget>();
2405
2406 // Pseudo shift instructions with a non constant shift amount are expanded
2407 // into a loop.
2408 switch (Opc) {
2409 case AVR::Lsl8:
2410 case AVR::Lsl16:
2411 case AVR::Lsr8:
2412 case AVR::Lsr16:
2413 case AVR::Rol8:
2414 case AVR::Rol16:
2415 case AVR::Ror8:
2416 case AVR::Ror16:
2417 case AVR::Asr8:
2418 case AVR::Asr16:
2419 return insertShift(MI, MBB, STI.hasTinyEncoding());
2420 case AVR::Lsl32:
2421 case AVR::Lsr32:
2422 case AVR::Asr32:
2423 return insertWideShift(MI, MBB);
2424 case AVR::MULRdRr:
2425 case AVR::MULSRdRr:
2426 return insertMul(MI, MBB);
2427 case AVR::CopyZero:
2428 return insertCopyZero(MI, MBB);
2429 case AVR::AtomicLoadAdd8:
2430 return insertAtomicArithmeticOp(MI, MBB, AVR::ADDRdRr, 8);
2431 case AVR::AtomicLoadAdd16:
2432 return insertAtomicArithmeticOp(MI, MBB, AVR::ADDWRdRr, 16);
2433 case AVR::AtomicLoadSub8:
2434 return insertAtomicArithmeticOp(MI, MBB, AVR::SUBRdRr, 8);
2435 case AVR::AtomicLoadSub16:
2436 return insertAtomicArithmeticOp(MI, MBB, AVR::SUBWRdRr, 16);
2437 case AVR::AtomicLoadAnd8:
2438 return insertAtomicArithmeticOp(MI, MBB, AVR::ANDRdRr, 8);
2439 case AVR::AtomicLoadAnd16:
2440 return insertAtomicArithmeticOp(MI, MBB, AVR::ANDWRdRr, 16);
2441 case AVR::AtomicLoadOr8:
2442 return insertAtomicArithmeticOp(MI, MBB, AVR::ORRdRr, 8);
2443 case AVR::AtomicLoadOr16:
2444 return insertAtomicArithmeticOp(MI, MBB, AVR::ORWRdRr, 16);
2445 case AVR::AtomicLoadXor8:
2446 return insertAtomicArithmeticOp(MI, MBB, AVR::EORRdRr, 8);
2447 case AVR::AtomicLoadXor16:
2448 return insertAtomicArithmeticOp(MI, MBB, AVR::EORWRdRr, 16);
2449 }
2450
2451 assert((Opc == AVR::Select16 || Opc == AVR::Select8) &&
2452 "Unexpected instr type to insert");
2453
2454 const AVRInstrInfo &TII = (const AVRInstrInfo &)*MI.getParent()
2455 ->getParent()
2456 ->getSubtarget()
2457 .getInstrInfo();
2458 DebugLoc dl = MI.getDebugLoc();
2459
2460 // To "insert" a SELECT instruction, we insert the diamond
2461 // control-flow pattern. The incoming instruction knows the
2462 // destination vreg to set, the condition code register to branch
2463 // on, the true/false values to select between, and a branch opcode
2464 // to use.
2465
2466 MachineFunction *MF = MBB->getParent();
2467 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
2468 MachineBasicBlock *FallThrough = MBB->getFallThrough();
2469
2470 // If the current basic block falls through to another basic block,
2471 // we must insert an unconditional branch to the fallthrough destination
2472 // if we are to insert basic blocks at the prior fallthrough point.
2473 if (FallThrough != nullptr) {
2474 BuildMI(MBB, dl, TII.get(AVR::RJMPk)).addMBB(FallThrough);
2475 }
2476
2477 MachineBasicBlock *trueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
2478 MachineBasicBlock *falseMBB = MF->CreateMachineBasicBlock(LLVM_BB);
2479
2481 for (I = MF->begin(); I != MF->end() && &(*I) != MBB; ++I)
2482 ;
2483 if (I != MF->end())
2484 ++I;
2485 MF->insert(I, trueMBB);
2486 MF->insert(I, falseMBB);
2487
2488 // Set the call frame size on entry to the new basic blocks.
2489 unsigned CallFrameSize = TII.getCallFrameSizeAt(MI);
2490 trueMBB->setCallFrameSize(CallFrameSize);
2491 falseMBB->setCallFrameSize(CallFrameSize);
2492
2493 // Transfer remaining instructions and all successors of the current
2494 // block to the block which will contain the Phi node for the
2495 // select.
2496 trueMBB->splice(trueMBB->begin(), MBB,
2497 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
2499
2500 AVRCC::CondCodes CC = (AVRCC::CondCodes)MI.getOperand(3).getImm();
2501 BuildMI(MBB, dl, TII.getBrCond(CC)).addMBB(trueMBB);
2502 BuildMI(MBB, dl, TII.get(AVR::RJMPk)).addMBB(falseMBB);
2503 MBB->addSuccessor(falseMBB);
2504 MBB->addSuccessor(trueMBB);
2505
2506 // Unconditionally flow back to the true block
2507 BuildMI(falseMBB, dl, TII.get(AVR::RJMPk)).addMBB(trueMBB);
2508 falseMBB->addSuccessor(trueMBB);
2509
2510 // Set up the Phi node to determine where we came from
2511 BuildMI(*trueMBB, trueMBB->begin(), dl, TII.get(AVR::PHI),
2512 MI.getOperand(0).getReg())
2513 .addReg(MI.getOperand(1).getReg())
2514 .addMBB(MBB)
2515 .addReg(MI.getOperand(2).getReg())
2516 .addMBB(falseMBB);
2517
2518 MI.eraseFromParent(); // The pseudo instruction is gone now.
2519 return trueMBB;
2520}
2521
2522//===----------------------------------------------------------------------===//
2523// Inline Asm Support
2524//===----------------------------------------------------------------------===//
2525
2528 if (Constraint.size() == 1) {
2529 // See http://www.nongnu.org/avr-libc/user-manual/inline_asm.html
2530 switch (Constraint[0]) {
2531 default:
2532 break;
2533 case 'a': // Simple upper registers
2534 case 'b': // Base pointer registers pairs
2535 case 'd': // Upper register
2536 case 'l': // Lower registers
2537 case 'e': // Pointer register pairs
2538 case 'q': // Stack pointer register
2539 case 'r': // Any register
2540 case 'w': // Special upper register pairs
2541 return C_RegisterClass;
2542 case 't': // Temporary register
2543 case 'x':
2544 case 'X': // Pointer register pair X
2545 case 'y':
2546 case 'Y': // Pointer register pair Y
2547 case 'z':
2548 case 'Z': // Pointer register pair Z
2549 return C_Register;
2550 case 'Q': // A memory address based on Y or Z pointer with displacement.
2551 return C_Memory;
2552 case 'G': // Floating point constant
2553 case 'I': // 6-bit positive integer constant
2554 case 'J': // 6-bit negative integer constant
2555 case 'K': // Integer constant (Range: 2)
2556 case 'L': // Integer constant (Range: 0)
2557 case 'M': // 8-bit integer constant
2558 case 'N': // Integer constant (Range: -1)
2559 case 'O': // Integer constant (Range: 8, 16, 24)
2560 case 'P': // Integer constant (Range: 1)
2561 case 'R': // Integer constant (Range: -6 to 5)x
2562 return C_Immediate;
2563 }
2564 }
2565
2566 return TargetLowering::getConstraintType(Constraint);
2567}
2568
2571 // Not sure if this is actually the right thing to do, but we got to do
2572 // *something* [agnat]
2573 switch (ConstraintCode[0]) {
2574 case 'Q':
2576 }
2577 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
2578}
2579
2582 AsmOperandInfo &info, const char *constraint) const {
2584 Value *CallOperandVal = info.CallOperandVal;
2585
2586 // If we don't have a value, we can't do a match,
2587 // but allow it at the lowest weight.
2588 // (this behaviour has been copied from the ARM backend)
2589 if (!CallOperandVal) {
2590 return CW_Default;
2591 }
2592
2593 // Look at the constraint type.
2594 switch (*constraint) {
2595 default:
2597 break;
2598 case 'd':
2599 case 'r':
2600 case 'l':
2601 weight = CW_Register;
2602 break;
2603 case 'a':
2604 case 'b':
2605 case 'e':
2606 case 'q':
2607 case 't':
2608 case 'w':
2609 case 'x':
2610 case 'X':
2611 case 'y':
2612 case 'Y':
2613 case 'z':
2614 case 'Z':
2615 weight = CW_SpecificReg;
2616 break;
2617 case 'G':
2618 if (const ConstantFP *C = dyn_cast<ConstantFP>(CallOperandVal)) {
2619 if (C->isZero()) {
2620 weight = CW_Constant;
2621 }
2622 }
2623 break;
2624 case 'I':
2625 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2626 if (isUInt<6>(C->getZExtValue())) {
2627 weight = CW_Constant;
2628 }
2629 }
2630 break;
2631 case 'J':
2632 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2633 if ((C->getSExtValue() >= -63) && (C->getSExtValue() <= 0)) {
2634 weight = CW_Constant;
2635 }
2636 }
2637 break;
2638 case 'K':
2639 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2640 if (C->getZExtValue() == 2) {
2641 weight = CW_Constant;
2642 }
2643 }
2644 break;
2645 case 'L':
2646 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2647 if (C->getZExtValue() == 0) {
2648 weight = CW_Constant;
2649 }
2650 }
2651 break;
2652 case 'M':
2653 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2654 if (isUInt<8>(C->getZExtValue())) {
2655 weight = CW_Constant;
2656 }
2657 }
2658 break;
2659 case 'N':
2660 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2661 if (C->getSExtValue() == -1) {
2662 weight = CW_Constant;
2663 }
2664 }
2665 break;
2666 case 'O':
2667 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2668 if ((C->getZExtValue() == 8) || (C->getZExtValue() == 16) ||
2669 (C->getZExtValue() == 24)) {
2670 weight = CW_Constant;
2671 }
2672 }
2673 break;
2674 case 'P':
2675 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2676 if (C->getZExtValue() == 1) {
2677 weight = CW_Constant;
2678 }
2679 }
2680 break;
2681 case 'R':
2682 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2683 if ((C->getSExtValue() >= -6) && (C->getSExtValue() <= 5)) {
2684 weight = CW_Constant;
2685 }
2686 }
2687 break;
2688 case 'Q':
2689 weight = CW_Memory;
2690 break;
2691 }
2692
2693 return weight;
2694}
2695
2696std::pair<unsigned, const TargetRegisterClass *>
2698 StringRef Constraint,
2699 MVT VT) const {
2700 if (Constraint.size() == 1) {
2701 switch (Constraint[0]) {
2702 case 'a': // Simple upper registers r16..r23.
2703 if (VT == MVT::i8)
2704 return std::make_pair(0U, &AVR::LD8loRegClass);
2705 else if (VT == MVT::i16)
2706 return std::make_pair(0U, &AVR::DREGSLD8loRegClass);
2707 break;
2708 case 'b': // Base pointer registers: y, z.
2709 if (VT == MVT::i8 || VT == MVT::i16)
2710 return std::make_pair(0U, &AVR::PTRDISPREGSRegClass);
2711 break;
2712 case 'd': // Upper registers r16..r31.
2713 if (VT == MVT::i8)
2714 return std::make_pair(0U, &AVR::LD8RegClass);
2715 else if (VT == MVT::i16)
2716 return std::make_pair(0U, &AVR::DLDREGSRegClass);
2717 break;
2718 case 'l': // Lower registers r0..r15.
2719 if (VT == MVT::i8)
2720 return std::make_pair(0U, &AVR::GPR8loRegClass);
2721 else if (VT == MVT::i16)
2722 return std::make_pair(0U, &AVR::DREGSloRegClass);
2723 break;
2724 case 'e': // Pointer register pairs: x, y, z.
2725 if (VT == MVT::i8 || VT == MVT::i16)
2726 return std::make_pair(0U, &AVR::PTRREGSRegClass);
2727 break;
2728 case 'q': // Stack pointer register: SPH:SPL.
2729 return std::make_pair(0U, &AVR::GPRSPRegClass);
2730 case 'r': // Any register: r0..r31.
2731 if (VT == MVT::i8)
2732 return std::make_pair(0U, &AVR::GPR8RegClass);
2733 else if (VT == MVT::i16)
2734 return std::make_pair(0U, &AVR::DREGSRegClass);
2735 break;
2736 case 't': // Temporary register: r0.
2737 if (VT == MVT::i8)
2738 return std::make_pair(unsigned(Subtarget.getTmpRegister()),
2739 &AVR::GPR8RegClass);
2740 break;
2741 case 'w': // Special upper register pairs: r24, r26, r28, r30.
2742 if (VT == MVT::i8 || VT == MVT::i16)
2743 return std::make_pair(0U, &AVR::IWREGSRegClass);
2744 break;
2745 case 'x': // Pointer register pair X: r27:r26.
2746 case 'X':
2747 if (VT == MVT::i8 || VT == MVT::i16)
2748 return std::make_pair(unsigned(AVR::R27R26), &AVR::PTRREGSRegClass);
2749 break;
2750 case 'y': // Pointer register pair Y: r29:r28.
2751 case 'Y':
2752 if (VT == MVT::i8 || VT == MVT::i16)
2753 return std::make_pair(unsigned(AVR::R29R28), &AVR::PTRREGSRegClass);
2754 break;
2755 case 'z': // Pointer register pair Z: r31:r30.
2756 case 'Z':
2757 if (VT == MVT::i8 || VT == MVT::i16)
2758 return std::make_pair(unsigned(AVR::R31R30), &AVR::PTRREGSRegClass);
2759 break;
2760 default:
2761 break;
2762 }
2763 }
2764
2766 Subtarget.getRegisterInfo(), Constraint, VT);
2767}
2768
2770 StringRef Constraint,
2771 std::vector<SDValue> &Ops,
2772 SelectionDAG &DAG) const {
2773 SDValue Result;
2774 SDLoc DL(Op);
2775 EVT Ty = Op.getValueType();
2776
2777 // Currently only support length 1 constraints.
2778 if (Constraint.size() != 1) {
2779 return;
2780 }
2781
2782 char ConstraintLetter = Constraint[0];
2783 switch (ConstraintLetter) {
2784 default:
2785 break;
2786 // Deal with integers first:
2787 case 'I':
2788 case 'J':
2789 case 'K':
2790 case 'L':
2791 case 'M':
2792 case 'N':
2793 case 'O':
2794 case 'P':
2795 case 'R': {
2797 if (!C) {
2798 return;
2799 }
2800
2801 int64_t CVal64 = C->getSExtValue();
2802 uint64_t CUVal64 = C->getZExtValue();
2803 switch (ConstraintLetter) {
2804 case 'I': // 0..63
2805 if (!isUInt<6>(CUVal64))
2806 return;
2807 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
2808 break;
2809 case 'J': // -63..0
2810 if (CVal64 < -63 || CVal64 > 0)
2811 return;
2812 Result = DAG.getTargetConstant(CVal64, DL, Ty);
2813 break;
2814 case 'K': // 2
2815 if (CUVal64 != 2)
2816 return;
2817 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
2818 break;
2819 case 'L': // 0
2820 if (CUVal64 != 0)
2821 return;
2822 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
2823 break;
2824 case 'M': // 0..255
2825 if (!isUInt<8>(CUVal64))
2826 return;
2827 // i8 type may be printed as a negative number,
2828 // e.g. 254 would be printed as -2,
2829 // so we force it to i16 at least.
2830 if (Ty.getSimpleVT() == MVT::i8) {
2831 Ty = MVT::i16;
2832 }
2833 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
2834 break;
2835 case 'N': // -1
2836 if (CVal64 != -1)
2837 return;
2838 Result = DAG.getTargetConstant(CVal64, DL, Ty);
2839 break;
2840 case 'O': // 8, 16, 24
2841 if (CUVal64 != 8 && CUVal64 != 16 && CUVal64 != 24)
2842 return;
2843 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
2844 break;
2845 case 'P': // 1
2846 if (CUVal64 != 1)
2847 return;
2848 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
2849 break;
2850 case 'R': // -6..5
2851 if (CVal64 < -6 || CVal64 > 5)
2852 return;
2853 Result = DAG.getTargetConstant(CVal64, DL, Ty);
2854 break;
2855 }
2856
2857 break;
2858 }
2859 case 'G':
2861 if (!FC || !FC->isZero())
2862 return;
2863 // Soften float to i8 0
2864 Result = DAG.getTargetConstant(0, DL, MVT::i8);
2865 break;
2866 }
2867
2868 if (Result.getNode()) {
2869 Ops.push_back(Result);
2870 return;
2871 }
2872
2873 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
2874}
2875
2877 const MachineFunction &MF) const {
2878 Register Reg;
2879
2880 if (VT == LLT::scalar(8)) {
2882 .Case("r0", AVR::R0)
2883 .Case("r1", AVR::R1)
2884 .Default(0);
2885 } else {
2887 .Case("r0", AVR::R1R0)
2888 .Case("sp", AVR::SP)
2889 .Default(0);
2890 }
2891
2892 if (Reg)
2893 return Reg;
2894
2896 Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
2897}
2898
2899} // end of namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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")
const HexagonInstrInfo * TII
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
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
const AVRInstrInfo * getInstrInfo() const override
const AVRRegisterInfo * getRegisterInfo() const override
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:126
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:467
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 integer and floating point boolean values from i1 to a w...
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:348
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:74
@ ProgramMemory
Definition AVR.h:44
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:845
@ 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:805
@ 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:879
@ 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:870
@ BR_CC
BR_CC - Conditional branch.
@ BR_JT
BR_JT - Jumptable branch.
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:822
@ 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:714
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:787
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:876
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:837
@ 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:914
@ 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:757
@ 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:882
@ 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:859
@ 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:880
#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:396
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
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.