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