1//===-- AVRFrameLowering.cpp - AVR Frame Information ----------------------===//
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 contains the AVR implementation of TargetFrameLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "AVRFrameLowering.h"
14
15#include "AVR.h"
16#include "AVRInstrInfo.h"
17#include "AVRMachineFunctionInfo.h"
18#include "AVRTargetMachine.h"
19#include "MCTargetDesc/AVRMCTargetDesc.h"
20
21#include "llvm/CodeGen/MachineFrameInfo.h"
22#include "llvm/CodeGen/MachineFunction.h"
23#include "llvm/CodeGen/MachineFunctionPass.h"
24#include "llvm/CodeGen/MachineInstrBuilder.h"
25#include "llvm/CodeGen/MachineRegisterInfo.h"
26#include "llvm/CodeGen/TargetFrameLowering.h"
27#include "llvm/Support/ErrorHandling.h"
28
29namespace llvm {
30
31AVRFrameLowering::AVRFrameLowering()
32 : TargetFrameLowering(TargetFrameLowering::StackGrowsDown, Align(1), -2) {}
33
34bool AVRFrameLowering::canSimplifyCallFramePseudos(
35 const MachineFunction &MF) const {
36 // Always simplify call frame pseudo instructions, even when
37 // hasReservedCallFrame is false.
38 return true;
39}
40
41bool AVRFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
42 // Reserve call frame memory in function prologue under the following
43 // conditions:
44 // - Y pointer is reserved to be the frame pointer.
45 // - The function does not contain variable sized objects.
46
47 const MachineFrameInfo &MFI = MF.getFrameInfo();
48 return hasFP(MF) && !MFI.hasVarSizedObjects();
49}
50
51void AVRFrameLowering::emitPrologue(MachineFunction &MF,
52 MachineBasicBlock &MBB) const {
53 MachineBasicBlock::iterator MBBI = MBB.begin();
54 DebugLoc DL = (MBBI != MBB.end()) ? MBBI->getDebugLoc() : DebugLoc();
55 const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>();
56 const AVRInstrInfo &TII = *STI.getInstrInfo();
57 const AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>();
58 const MachineRegisterInfo &MRI = MF.getRegInfo();
59 bool HasFP = hasFP(MF);
60
61 // Interrupt handlers re-enable interrupts in function entry.
62 if (AFI->isInterruptHandler()) {
63 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: AVR::BSETs))
64 .addImm(Val: 0x07)
65 .setMIFlag(MachineInstr::FrameSetup);
66 }
67
68 // Emit special prologue code to save R1, R0 and SREG in interrupt/signal
69 // handlers before saving any other registers.
70 if (AFI->isInterruptOrSignalHandler()) {
71 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: AVR::PUSHRr))
72 .addReg(RegNo: STI.getTmpRegister(), Flags: RegState::Kill)
73 .setMIFlag(MachineInstr::FrameSetup);
74
75 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: AVR::INRdA), DestReg: STI.getTmpRegister())
76 .addImm(Val: STI.getIORegSREG())
77 .setMIFlag(MachineInstr::FrameSetup);
78 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: AVR::PUSHRr))
79 .addReg(RegNo: STI.getTmpRegister(), Flags: RegState::Kill)
80 .setMIFlag(MachineInstr::FrameSetup);
81 if (!MRI.reg_empty(RegNo: STI.getZeroRegister())) {
82 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: AVR::PUSHRr))
83 .addReg(RegNo: STI.getZeroRegister(), Flags: RegState::Kill)
84 .setMIFlag(MachineInstr::FrameSetup);
85 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: AVR::EORRdRr))
86 .addReg(RegNo: STI.getZeroRegister(), Flags: RegState::Define)
87 .addReg(RegNo: STI.getZeroRegister(), Flags: RegState::Kill)
88 .addReg(RegNo: STI.getZeroRegister(), Flags: RegState::Kill)
89 .setMIFlag(MachineInstr::FrameSetup);
90 }
91 }
92
93 // Early exit if the frame pointer is not needed in this function.
94 if (!HasFP) {
95 return;
96 }
97
98 const MachineFrameInfo &MFI = MF.getFrameInfo();
99 unsigned FrameSize = MFI.getStackSize() - AFI->getCalleeSavedFrameSize();
100
101 // Skip the callee-saved push instructions.
102 while (
103 (MBBI != MBB.end()) && MBBI->getFlag(Flag: MachineInstr::FrameSetup) &&
104 (MBBI->getOpcode() == AVR::PUSHRr || MBBI->getOpcode() == AVR::PUSHWRr)) {
105 ++MBBI;
106 }
107
108 // Update Y with the new base value.
109 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: AVR::SPREAD), DestReg: AVR::R29R28)
110 .addReg(RegNo: AVR::SP)
111 .setMIFlag(MachineInstr::FrameSetup);
112
113 // Mark the FramePtr as live-in in every block except the entry.
114 for (MachineBasicBlock &MBBJ : llvm::drop_begin(RangeOrContainer&: MF)) {
115 MBBJ.addLiveIn(PhysReg: AVR::R29R28);
116 }
117
118 if (!FrameSize) {
119 return;
120 }
121
122 // Reserve the necessary frame memory by doing FP -= <size>.
123 unsigned Opcode = (isUInt<6>(x: FrameSize) && STI.hasADDSUBIW()) ? AVR::SBIWRdK
124 : AVR::SUBIWRdK;
125
126 MachineInstr *MI = BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode), DestReg: AVR::R29R28)
127 .addReg(RegNo: AVR::R29R28, Flags: RegState::Kill)
128 .addImm(Val: FrameSize)
129 .setMIFlag(MachineInstr::FrameSetup);
130 // The SREG implicit def is dead.
131 MI->getOperand(i: 3).setIsDead();
132
133 // Write back R29R28 to SP and temporarily disable interrupts.
134 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: AVR::SPWRITE), DestReg: AVR::SP)
135 .addReg(RegNo: AVR::R29R28)
136 .setMIFlag(MachineInstr::FrameSetup);
137}
138
139static void restoreStatusRegister(MachineFunction &MF, MachineBasicBlock &MBB) {
140 const AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>();
141 const MachineRegisterInfo &MRI = MF.getRegInfo();
142
143 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
144
145 DebugLoc DL = MBBI->getDebugLoc();
146 const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>();
147 const AVRInstrInfo &TII = *STI.getInstrInfo();
148
149 // Emit special epilogue code to restore R1, R0 and SREG in interrupt/signal
150 // handlers at the very end of the function, just before reti.
151 if (AFI->isInterruptOrSignalHandler()) {
152 if (!MRI.reg_empty(RegNo: STI.getZeroRegister())) {
153 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: AVR::POPRd), DestReg: STI.getZeroRegister());
154 }
155 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: AVR::POPRd), DestReg: STI.getTmpRegister());
156 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: AVR::OUTARr))
157 .addImm(Val: STI.getIORegSREG())
158 .addReg(RegNo: STI.getTmpRegister(), Flags: RegState::Kill);
159 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: AVR::POPRd), DestReg: STI.getTmpRegister());
160 }
161}
162
163void AVRFrameLowering::emitEpilogue(MachineFunction &MF,
164 MachineBasicBlock &MBB) const {
165 const AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>();
166
167 // Early exit if the frame pointer is not needed in this function except for
168 // signal/interrupt handlers where special code generation is required.
169 if (!hasFP(MF) && !AFI->isInterruptOrSignalHandler()) {
170 return;
171 }
172
173 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
174 assert(MBBI->getDesc().isReturn() &&
175 "Can only insert epilog into returning blocks");
176
177 DebugLoc DL = MBBI->getDebugLoc();
178 const MachineFrameInfo &MFI = MF.getFrameInfo();
179 unsigned FrameSize = MFI.getStackSize() - AFI->getCalleeSavedFrameSize();
180 const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>();
181 const AVRInstrInfo &TII = *STI.getInstrInfo();
182
183 // Early exit if there is no need to restore the frame pointer.
184 if (!FrameSize && !MF.getFrameInfo().hasVarSizedObjects()) {
185 restoreStatusRegister(MF, MBB);
186 return;
187 }
188
189 // Skip the callee-saved pop instructions.
190 while (MBBI != MBB.begin()) {
191 MachineBasicBlock::iterator PI = std::prev(x: MBBI);
192 int Opc = PI->getOpcode();
193
194 if (Opc != AVR::POPRd && Opc != AVR::POPWRd && !PI->isTerminator()) {
195 break;
196 }
197
198 --MBBI;
199 }
200
201 if (FrameSize) {
202 // Restore the frame pointer by doing FP += <size>.
203 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: AVR::ADIWRdKP), DestReg: AVR::R29R28)
204 .addReg(RegNo: AVR::R29R28, Flags: RegState::Kill)
205 .addImm(Val: FrameSize)
206 .setOperandDead(3); // implicit-def $sreg
207 }
208
209 // Write back R29R28 to SP and temporarily disable interrupts.
210 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: AVR::SPWRITE), DestReg: AVR::SP)
211 .addReg(RegNo: AVR::R29R28, Flags: RegState::Kill);
212
213 restoreStatusRegister(MF, MBB);
214}
215
216StackOffset AVRFrameLowering::getFrameIndexReference(const MachineFunction &MF,
217 int FI,
218 Register &FrameReg) const {
219 int64_t Offset;
220 const MachineFrameInfo &MFI = MF.getFrameInfo();
221
222 switch (MFI.getStackID(ObjectIdx: FI)) {
223 case TargetStackID::Default:
224 Offset = MFI.getObjectOffset(ObjectIdx: FI) + MFI.getOffsetAdjustment() +
225 MFI.getStackSize() - getOffsetOfLocalArea() + 1;
226
227 assert(Offset > 0);
228 break;
229
230 case TargetStackID::AvrAlign:
231 Offset = MFI.getObjectOffset(ObjectIdx: FI);
232 assert(Offset >= 0);
233 break;
234
235 default:
236 llvm_unreachable("Unsupported stack!");
237 }
238
239 return StackOffset::getFixed(Fixed: Offset);
240}
241
242// Return true if the specified function should have a dedicated frame
243// pointer register. This is true if the function meets any of the following
244// conditions:
245// - a register has been spilled
246// - has allocas
247// - input arguments are passed using the stack
248// - has variable sized objects
249// - the frame address is taken (llvm.frameaddress)
250// - the return address is taken (llvm.returnaddress)
251//
252// Notice that strictly this is not a frame pointer because it contains SP after
253// frame allocation instead of having the original SP in function entry.
254bool AVRFrameLowering::hasFPImpl(const MachineFunction &MF) const {
255 const MachineFrameInfo &MFI = MF.getFrameInfo();
256 const AVRMachineFunctionInfo *FuncInfo = MF.getInfo<AVRMachineFunctionInfo>();
257
258 // Note that reading the return address requires a frame index, and that frame
259 // indexes are always referenced through Y (see
260 // AVRRegisterInfo::eliminateFrameIndex).
261 return (FuncInfo->getHasSpills() || FuncInfo->getHasAllocas() ||
262 FuncInfo->getHasStackArgs() || MFI.hasVarSizedObjects() ||
263 MFI.isFrameAddressTaken() || MFI.isReturnAddressTaken());
264}
265
266bool AVRFrameLowering::spillCalleeSavedRegisters(
267 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
268 ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
269 if (CSI.empty()) {
270 return false;
271 }
272
273 unsigned CalleeFrameSize = 0;
274 DebugLoc DL = MBB.findDebugLoc(MBBI: MI);
275 MachineFunction &MF = *MBB.getParent();
276 const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>();
277 const TargetInstrInfo &TII = *STI.getInstrInfo();
278 AVRMachineFunctionInfo *AVRFI = MF.getInfo<AVRMachineFunctionInfo>();
279
280 for (const CalleeSavedInfo &I : llvm::reverse(C&: CSI)) {
281 MCRegister Reg = I.getReg();
282 bool IsNotLiveIn = !MBB.isLiveIn(Reg);
283
284 // Check if Reg is a sub register of a 16-bit livein register, and then
285 // add it to the livein list.
286 if (IsNotLiveIn)
287 for (const auto &LiveIn : MBB.liveins())
288 if (STI.getRegisterInfo()->isSubRegister(RegA: LiveIn.PhysReg, RegB: Reg)) {
289 IsNotLiveIn = false;
290 MBB.addLiveIn(PhysReg: Reg);
291 break;
292 }
293
294 assert(TRI->getRegSizeInBits(*TRI->getMinimalPhysRegClass(Reg)) == 8 &&
295 "Invalid register size");
296
297 // Add the callee-saved register as live-in only if it is not already a
298 // live-in register, this usually happens with arguments that are passed
299 // through callee-saved registers.
300 if (IsNotLiveIn) {
301 MBB.addLiveIn(PhysReg: Reg);
302 }
303
304 // Do not kill the register when it is an input argument.
305 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: AVR::PUSHRr))
306 .addReg(RegNo: Reg, Flags: getKillRegState(B: IsNotLiveIn))
307 .setMIFlag(MachineInstr::FrameSetup);
308 ++CalleeFrameSize;
309 }
310
311 AVRFI->setCalleeSavedFrameSize(CalleeFrameSize);
312
313 return true;
314}
315
316bool AVRFrameLowering::restoreCalleeSavedRegisters(
317 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
318 MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
319 if (CSI.empty()) {
320 return false;
321 }
322
323 DebugLoc DL = MBB.findDebugLoc(MBBI: MI);
324 const MachineFunction &MF = *MBB.getParent();
325 const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>();
326 const TargetInstrInfo &TII = *STI.getInstrInfo();
327
328 for (const CalleeSavedInfo &CCSI : CSI) {
329 MCRegister Reg = CCSI.getReg();
330
331 assert(TRI->getRegSizeInBits(*TRI->getMinimalPhysRegClass(Reg)) == 8 &&
332 "Invalid register size");
333
334 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: AVR::POPRd), DestReg: Reg);
335 }
336
337 return true;
338}
339
340/// Replace pseudo store instructions that pass arguments through the stack with
341/// real instructions.
342static void fixStackStores(MachineBasicBlock &MBB,
343 MachineBasicBlock::iterator StartMI,
344 const TargetInstrInfo &TII) {
345 // Iterate through the BB until we hit a call instruction or we reach the end.
346 for (MachineInstr &MI :
347 llvm::make_early_inc_range(Range: llvm::make_range(x: StartMI, y: MBB.end()))) {
348 if (MI.isCall())
349 break;
350
351 unsigned Opcode = MI.getOpcode();
352
353 // Only care of pseudo store instructions where SP is the base pointer.
354 if (Opcode != AVR::STDSPQRr && Opcode != AVR::STDWSPQRr)
355 continue;
356
357 assert(MI.getOperand(0).getReg() == AVR::SP &&
358 "SP is expected as base pointer");
359
360 // Replace this instruction with a regular store. Use Y as the base
361 // pointer since it is guaranteed to contain a copy of SP.
362 unsigned STOpc =
363 (Opcode == AVR::STDWSPQRr) ? AVR::STDWPtrQRr : AVR::STDPtrQRr;
364
365 MI.setDesc(TII.get(Opcode: STOpc));
366 MI.getOperand(i: 0).setReg(AVR::R31R30);
367 }
368}
369
370MachineBasicBlock::iterator AVRFrameLowering::eliminateCallFramePseudoInstr(
371 MachineFunction &MF, MachineBasicBlock &MBB,
372 MachineBasicBlock::iterator MI) const {
373 const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>();
374 const AVRInstrInfo &TII = *STI.getInstrInfo();
375
376 if (hasReservedCallFrame(MF)) {
377 return MBB.erase(I: MI);
378 }
379
380 DebugLoc DL = MI->getDebugLoc();
381 unsigned int Opcode = MI->getOpcode();
382 int Amount = TII.getFrameSize(I: *MI);
383
384 if (Amount == 0) {
385 return MBB.erase(I: MI);
386 }
387
388 assert(getStackAlign() == Align(1) && "Unsupported stack alignment");
389
390 if (Opcode == TII.getCallFrameSetupOpcode()) {
391 // Update the stack pointer.
392 // In many cases this can be done far more efficiently by pushing the
393 // relevant values directly to the stack. However, doing that correctly
394 // (in the right order, possibly skipping some empty space for undef
395 // values, etc) is tricky and thus left to be optimized in the future.
396 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: AVR::SPREAD), DestReg: AVR::R31R30).addReg(RegNo: AVR::SP);
397
398 MachineInstr *New =
399 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: AVR::SUBIWRdK), DestReg: AVR::R31R30)
400 .addReg(RegNo: AVR::R31R30, Flags: RegState::Kill)
401 .addImm(Val: Amount);
402 New->getOperand(i: 3).setIsDead();
403
404 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: AVR::SPWRITE), DestReg: AVR::SP).addReg(RegNo: AVR::R31R30);
405
406 // Make sure the remaining stack stores are converted to real store
407 // instructions.
408 fixStackStores(MBB, StartMI: MI, TII);
409 } else {
410 assert(Opcode == TII.getCallFrameDestroyOpcode());
411
412 // Note that small stack changes could be implemented more efficiently
413 // with a few pop instructions instead of the 8-9 instructions now
414 // required.
415
416 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: AVR::SPREAD), DestReg: AVR::R31R30).addReg(RegNo: AVR::SP);
417
418 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: AVR::ADIWRdKP), DestReg: AVR::R31R30)
419 .addReg(RegNo: AVR::R31R30, Flags: RegState::Kill)
420 .addImm(Val: Amount)
421 .setOperandDead(3); // implicit-def $sreg
422
423 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: AVR::SPWRITE), DestReg: AVR::SP)
424 .addReg(RegNo: AVR::R31R30, Flags: RegState::Kill);
425 }
426
427 return MBB.erase(I: MI);
428}
429
430void AVRFrameLowering::determineCalleeSaves(MachineFunction &MF,
431 BitVector &SavedRegs,
432 RegScavenger *RS) const {
433 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
434
435 // If we have a frame pointer, the Y register needs to be saved as well.
436 if (hasFP(MF)) {
437 SavedRegs.set(AVR::R29);
438 SavedRegs.set(AVR::R28);
439 }
440}
441
442/// The frame analyzer pass.
443///
444/// Scans the function for allocas and used arguments
445/// that are passed through the stack.
446struct AVRFrameAnalyzer : public MachineFunctionPass {
447 static char ID;
448 AVRFrameAnalyzer() : MachineFunctionPass(ID) {}
449
450 bool runOnMachineFunction(MachineFunction &MF) override {
451 const MachineFrameInfo &MFI = MF.getFrameInfo();
452 AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>();
453
454 // If there are no fixed frame indexes during this stage it means there
455 // are allocas present in the function.
456 if (MFI.getNumObjects() != MFI.getNumFixedObjects()) {
457 // Check for the type of allocas present in the function. We only care
458 // about fixed size allocas so do not give false positives if only
459 // variable sized allocas are present.
460 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
461 if (!MFI.isVariableSizedObjectIndex(ObjectIdx: i) && !MFI.isDeadObjectIndex(ObjectIdx: i)) {
462 AFI->setHasAllocas(true);
463 break;
464 }
465 }
466 }
467
468 // If there are fixed frame indexes present, scan the function to see if
469 // they are really being used.
470 if (MFI.getNumFixedObjects() == 0) {
471 return false;
472 }
473
474 // Ok fixed frame indexes present, now scan the function to see if they
475 // are really being used, otherwise we can ignore them.
476 for (const MachineBasicBlock &BB : MF) {
477 for (const MachineInstr &MI : BB) {
478 int Opcode = MI.getOpcode();
479
480 if ((Opcode != AVR::LDDRdPtrQ) && (Opcode != AVR::LDDWRdPtrQ) &&
481 (Opcode != AVR::STDPtrQRr) && (Opcode != AVR::STDWPtrQRr) &&
482 (Opcode != AVR::FRMIDX)) {
483 continue;
484 }
485
486 for (const MachineOperand &MO : MI.operands()) {
487 if (!MO.isFI()) {
488 continue;
489 }
490
491 if (MFI.isFixedObjectIndex(ObjectIdx: MO.getIndex())) {
492 AFI->setHasStackArgs(true);
493 return false;
494 }
495 }
496 }
497 }
498
499 return false;
500 }
501
502 StringRef getPassName() const override { return "AVR Frame Analyzer"; }
503};
504
505char AVRFrameAnalyzer::ID = 0;
506
507/// Creates instance of the frame analyzer pass.
508FunctionPass *createAVRFrameAnalyzerPass() { return new AVRFrameAnalyzer(); }
509
510} // end of namespace llvm
511