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