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