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/IR/Function.h"
27 
28 #include <vector>
29 
30 namespace llvm {
31 
32 AVRFrameLowering::AVRFrameLowering()
33     : TargetFrameLowering(TargetFrameLowering::StackGrowsDown, Align(1), -2) {}
34 
35 bool AVRFrameLowering::canSimplifyCallFramePseudos(
36     const MachineFunction &MF) const {
37   // Always simplify call frame pseudo instructions, even when
38   // hasReservedCallFrame is false.
39   return true;
40 }
41 
42 bool AVRFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
43   // Reserve call frame memory in function prologue under the following
44   // conditions:
45   // - Y pointer is reserved to be the frame pointer.
46   // - The function does not contain variable sized objects.
47 
48   const MachineFrameInfo &MFI = MF.getFrameInfo();
49   return hasFP(MF) && !MFI.hasVarSizedObjects();
50 }
51 
52 void AVRFrameLowering::emitPrologue(MachineFunction &MF,
53                                     MachineBasicBlock &MBB) const {
54   MachineBasicBlock::iterator MBBI = MBB.begin();
55   DebugLoc DL = (MBBI != MBB.end()) ? MBBI->getDebugLoc() : DebugLoc();
56   const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>();
57   const AVRInstrInfo &TII = *STI.getInstrInfo();
58   const AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>();
59   bool HasFP = hasFP(MF);
60 
61   // Interrupt handlers re-enable interrupts in function entry.
62   if (AFI->isInterruptHandler()) {
63     BuildMI(MBB, MBBI, DL, TII.get(AVR::BSETs))
64         .addImm(0x07)
65         .setMIFlag(MachineInstr::FrameSetup);
66   }
67 
68   // Save the frame pointer if we have one.
69   if (HasFP) {
70     BuildMI(MBB, MBBI, DL, TII.get(AVR::PUSHWRr))
71         .addReg(AVR::R29R28, RegState::Kill)
72         .setMIFlag(MachineInstr::FrameSetup);
73   }
74 
75   // Emit special prologue code to save R1, R0 and SREG in interrupt/signal
76   // handlers before saving any other registers.
77   if (AFI->isInterruptOrSignalHandler()) {
78     BuildMI(MBB, MBBI, DL, TII.get(AVR::PUSHWRr))
79         .addReg(AVR::R1R0, RegState::Kill)
80         .setMIFlag(MachineInstr::FrameSetup);
81 
82     BuildMI(MBB, MBBI, DL, TII.get(AVR::INRdA), AVR::R0)
83         .addImm(0x3f)
84         .setMIFlag(MachineInstr::FrameSetup);
85     BuildMI(MBB, MBBI, DL, TII.get(AVR::PUSHRr))
86         .addReg(AVR::R0, RegState::Kill)
87         .setMIFlag(MachineInstr::FrameSetup);
88     BuildMI(MBB, MBBI, DL, TII.get(AVR::EORRdRr))
89         .addReg(AVR::R0, RegState::Define)
90         .addReg(AVR::R0, RegState::Kill)
91         .addReg(AVR::R0, RegState::Kill)
92         .setMIFlag(MachineInstr::FrameSetup);
93   }
94 
95   // Early exit if the frame pointer is not needed in this function.
96   if (!HasFP) {
97     return;
98   }
99 
100   const MachineFrameInfo &MFI = MF.getFrameInfo();
101   unsigned FrameSize = MFI.getStackSize() - AFI->getCalleeSavedFrameSize();
102 
103   // Skip the callee-saved push instructions.
104   while (
105       (MBBI != MBB.end()) && MBBI->getFlag(MachineInstr::FrameSetup) &&
106       (MBBI->getOpcode() == AVR::PUSHRr || MBBI->getOpcode() == AVR::PUSHWRr)) {
107     ++MBBI;
108   }
109 
110   // Update Y with the new base value.
111   BuildMI(MBB, MBBI, DL, TII.get(AVR::SPREAD), AVR::R29R28)
112       .addReg(AVR::SP)
113       .setMIFlag(MachineInstr::FrameSetup);
114 
115   // Mark the FramePtr as live-in in every block except the entry.
116   for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
117        I != E; ++I) {
118     I->addLiveIn(AVR::R29R28);
119   }
120 
121   if (!FrameSize) {
122     return;
123   }
124 
125   // Reserve the necessary frame memory by doing FP -= <size>.
126   unsigned Opcode = (isUInt<6>(FrameSize)) ? AVR::SBIWRdK : AVR::SUBIWRdK;
127 
128   MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opcode), AVR::R29R28)
129                          .addReg(AVR::R29R28, RegState::Kill)
130                          .addImm(FrameSize)
131                          .setMIFlag(MachineInstr::FrameSetup);
132   // The SREG implicit def is dead.
133   MI->getOperand(3).setIsDead();
134 
135   // Write back R29R28 to SP and temporarily disable interrupts.
136   BuildMI(MBB, MBBI, DL, TII.get(AVR::SPWRITE), AVR::SP)
137       .addReg(AVR::R29R28)
138       .setMIFlag(MachineInstr::FrameSetup);
139 }
140 
141 void AVRFrameLowering::emitEpilogue(MachineFunction &MF,
142                                     MachineBasicBlock &MBB) const {
143   const AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>();
144 
145   // Early exit if the frame pointer is not needed in this function except for
146   // signal/interrupt handlers where special code generation is required.
147   if (!hasFP(MF) && !AFI->isInterruptOrSignalHandler()) {
148     return;
149   }
150 
151   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
152   assert(MBBI->getDesc().isReturn() &&
153          "Can only insert epilog into returning blocks");
154 
155   DebugLoc DL = MBBI->getDebugLoc();
156   const MachineFrameInfo &MFI = MF.getFrameInfo();
157   unsigned FrameSize = MFI.getStackSize() - AFI->getCalleeSavedFrameSize();
158   const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>();
159   const AVRInstrInfo &TII = *STI.getInstrInfo();
160 
161   // Emit special epilogue code to restore R1, R0 and SREG in interrupt/signal
162   // handlers at the very end of the function, just before reti.
163   if (AFI->isInterruptOrSignalHandler()) {
164     BuildMI(MBB, MBBI, DL, TII.get(AVR::POPRd), AVR::R0);
165     BuildMI(MBB, MBBI, DL, TII.get(AVR::OUTARr))
166         .addImm(0x3f)
167         .addReg(AVR::R0, RegState::Kill);
168     BuildMI(MBB, MBBI, DL, TII.get(AVR::POPWRd), AVR::R1R0);
169   }
170 
171   if (hasFP(MF))
172     BuildMI(MBB, MBBI, DL, TII.get(AVR::POPWRd), AVR::R29R28);
173 
174   // Early exit if there is no need to restore the frame pointer.
175   if (!FrameSize) {
176     return;
177   }
178 
179   // Skip the callee-saved pop instructions.
180   while (MBBI != MBB.begin()) {
181     MachineBasicBlock::iterator PI = std::prev(MBBI);
182     int Opc = PI->getOpcode();
183 
184     if (Opc != AVR::POPRd && Opc != AVR::POPWRd && !PI->isTerminator()) {
185       break;
186     }
187 
188     --MBBI;
189   }
190 
191   unsigned Opcode;
192 
193   // Select the optimal opcode depending on how big it is.
194   if (isUInt<6>(FrameSize)) {
195     Opcode = AVR::ADIWRdK;
196   } else {
197     Opcode = AVR::SUBIWRdK;
198     FrameSize = -FrameSize;
199   }
200 
201   // Restore the frame pointer by doing FP += <size>.
202   MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opcode), AVR::R29R28)
203                          .addReg(AVR::R29R28, RegState::Kill)
204                          .addImm(FrameSize);
205   // The SREG implicit def is dead.
206   MI->getOperand(3).setIsDead();
207 
208   // Write back R29R28 to SP and temporarily disable interrupts.
209   BuildMI(MBB, MBBI, DL, TII.get(AVR::SPWRITE), AVR::SP)
210       .addReg(AVR::R29R28, RegState::Kill);
211 }
212 
213 // Return true if the specified function should have a dedicated frame
214 // pointer register. This is true if the function meets any of the following
215 // conditions:
216 //  - a register has been spilled
217 //  - has allocas
218 //  - input arguments are passed using the stack
219 //
220 // Notice that strictly this is not a frame pointer because it contains SP after
221 // frame allocation instead of having the original SP in function entry.
222 bool AVRFrameLowering::hasFP(const MachineFunction &MF) const {
223   const AVRMachineFunctionInfo *FuncInfo = MF.getInfo<AVRMachineFunctionInfo>();
224 
225   return (FuncInfo->getHasSpills() || FuncInfo->getHasAllocas() ||
226           FuncInfo->getHasStackArgs());
227 }
228 
229 bool AVRFrameLowering::spillCalleeSavedRegisters(
230     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
231     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
232   if (CSI.empty()) {
233     return false;
234   }
235 
236   unsigned CalleeFrameSize = 0;
237   DebugLoc DL = MBB.findDebugLoc(MI);
238   MachineFunction &MF = *MBB.getParent();
239   const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>();
240   const TargetInstrInfo &TII = *STI.getInstrInfo();
241   AVRMachineFunctionInfo *AVRFI = MF.getInfo<AVRMachineFunctionInfo>();
242 
243   for (unsigned i = CSI.size(); i != 0; --i) {
244     unsigned Reg = CSI[i - 1].getReg();
245     bool IsNotLiveIn = !MBB.isLiveIn(Reg);
246 
247     assert(TRI->getRegSizeInBits(*TRI->getMinimalPhysRegClass(Reg)) == 8 &&
248            "Invalid register size");
249 
250     // Add the callee-saved register as live-in only if it is not already a
251     // live-in register, this usually happens with arguments that are passed
252     // through callee-saved registers.
253     if (IsNotLiveIn) {
254       MBB.addLiveIn(Reg);
255     }
256 
257     // Do not kill the register when it is an input argument.
258     BuildMI(MBB, MI, DL, TII.get(AVR::PUSHRr))
259         .addReg(Reg, getKillRegState(IsNotLiveIn))
260         .setMIFlag(MachineInstr::FrameSetup);
261     ++CalleeFrameSize;
262   }
263 
264   AVRFI->setCalleeSavedFrameSize(CalleeFrameSize);
265 
266   return true;
267 }
268 
269 bool AVRFrameLowering::restoreCalleeSavedRegisters(
270     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
271     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
272   if (CSI.empty()) {
273     return false;
274   }
275 
276   DebugLoc DL = MBB.findDebugLoc(MI);
277   const MachineFunction &MF = *MBB.getParent();
278   const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>();
279   const TargetInstrInfo &TII = *STI.getInstrInfo();
280 
281   for (const CalleeSavedInfo &CCSI : CSI) {
282     unsigned Reg = CCSI.getReg();
283 
284     assert(TRI->getRegSizeInBits(*TRI->getMinimalPhysRegClass(Reg)) == 8 &&
285            "Invalid register size");
286 
287     BuildMI(MBB, MI, DL, TII.get(AVR::POPRd), Reg);
288   }
289 
290   return true;
291 }
292 
293 /// Replace pseudo store instructions that pass arguments through the stack with
294 /// real instructions. If insertPushes is true then all instructions are
295 /// replaced with push instructions, otherwise regular std instructions are
296 /// inserted.
297 static void fixStackStores(MachineBasicBlock &MBB,
298                            MachineBasicBlock::iterator MI,
299                            const TargetInstrInfo &TII, bool insertPushes) {
300   const AVRSubtarget &STI = MBB.getParent()->getSubtarget<AVRSubtarget>();
301   const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
302 
303   // Iterate through the BB until we hit a call instruction or we reach the end.
304   for (auto I = MI, E = MBB.end(); I != E && !I->isCall();) {
305     MachineBasicBlock::iterator NextMI = std::next(I);
306     MachineInstr &MI = *I;
307     unsigned Opcode = I->getOpcode();
308 
309     // Only care of pseudo store instructions where SP is the base pointer.
310     if (Opcode != AVR::STDSPQRr && Opcode != AVR::STDWSPQRr) {
311       I = NextMI;
312       continue;
313     }
314 
315     assert(MI.getOperand(0).getReg() == AVR::SP &&
316            "Invalid register, should be SP!");
317     if (insertPushes) {
318       // Replace this instruction with a push.
319       Register SrcReg = MI.getOperand(2).getReg();
320       bool SrcIsKill = MI.getOperand(2).isKill();
321 
322       // We can't use PUSHWRr here because when expanded the order of the new
323       // instructions are reversed from what we need. Perform the expansion now.
324       if (Opcode == AVR::STDWSPQRr) {
325         BuildMI(MBB, I, MI.getDebugLoc(), TII.get(AVR::PUSHRr))
326             .addReg(TRI.getSubReg(SrcReg, AVR::sub_hi),
327                     getKillRegState(SrcIsKill));
328         BuildMI(MBB, I, MI.getDebugLoc(), TII.get(AVR::PUSHRr))
329             .addReg(TRI.getSubReg(SrcReg, AVR::sub_lo),
330                     getKillRegState(SrcIsKill));
331       } else {
332         BuildMI(MBB, I, MI.getDebugLoc(), TII.get(AVR::PUSHRr))
333             .addReg(SrcReg, getKillRegState(SrcIsKill));
334       }
335 
336       MI.eraseFromParent();
337       I = NextMI;
338       continue;
339     }
340 
341     // Replace this instruction with a regular store. Use Y as the base
342     // pointer since it is guaranteed to contain a copy of SP.
343     unsigned STOpc =
344         (Opcode == AVR::STDWSPQRr) ? AVR::STDWPtrQRr : AVR::STDPtrQRr;
345 
346     MI.setDesc(TII.get(STOpc));
347     MI.getOperand(0).setReg(AVR::R29R28);
348 
349     I = NextMI;
350   }
351 }
352 
353 MachineBasicBlock::iterator AVRFrameLowering::eliminateCallFramePseudoInstr(
354     MachineFunction &MF, MachineBasicBlock &MBB,
355     MachineBasicBlock::iterator MI) const {
356   const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>();
357   const AVRInstrInfo &TII = *STI.getInstrInfo();
358 
359   // There is nothing to insert when the call frame memory is allocated during
360   // function entry. Delete the call frame pseudo and replace all pseudo stores
361   // with real store instructions.
362   if (hasReservedCallFrame(MF)) {
363     fixStackStores(MBB, MI, TII, false);
364     return MBB.erase(MI);
365   }
366 
367   DebugLoc DL = MI->getDebugLoc();
368   unsigned int Opcode = MI->getOpcode();
369   int Amount = TII.getFrameSize(*MI);
370 
371   // Adjcallstackup does not need to allocate stack space for the call, instead
372   // we insert push instructions that will allocate the necessary stack.
373   // For adjcallstackdown we convert it into an 'adiw reg, <amt>' handling
374   // the read and write of SP in I/O space.
375   if (Amount != 0) {
376     assert(getStackAlign() == Align(1) && "Unsupported stack alignment");
377 
378     if (Opcode == TII.getCallFrameSetupOpcode()) {
379       fixStackStores(MBB, MI, TII, true);
380     } else {
381       assert(Opcode == TII.getCallFrameDestroyOpcode());
382 
383       // Select the best opcode to adjust SP based on the offset size.
384       unsigned addOpcode;
385       if (isUInt<6>(Amount)) {
386         addOpcode = AVR::ADIWRdK;
387       } else {
388         addOpcode = AVR::SUBIWRdK;
389         Amount = -Amount;
390       }
391 
392       // Build the instruction sequence.
393       BuildMI(MBB, MI, DL, TII.get(AVR::SPREAD), AVR::R31R30).addReg(AVR::SP);
394 
395       MachineInstr *New = BuildMI(MBB, MI, DL, TII.get(addOpcode), AVR::R31R30)
396                               .addReg(AVR::R31R30, RegState::Kill)
397                               .addImm(Amount);
398       New->getOperand(3).setIsDead();
399 
400       BuildMI(MBB, MI, DL, TII.get(AVR::SPWRITE), AVR::SP)
401           .addReg(AVR::R31R30, RegState::Kill);
402     }
403   }
404 
405   return MBB.erase(MI);
406 }
407 
408 void AVRFrameLowering::determineCalleeSaves(MachineFunction &MF,
409                                             BitVector &SavedRegs,
410                                             RegScavenger *RS) const {
411   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
412 
413   // If we have a frame pointer, the Y register needs to be saved as well.
414   // We don't do that here however - the prologue and epilogue generation
415   // code will handle it specially.
416 }
417 /// The frame analyzer pass.
418 ///
419 /// Scans the function for allocas and used arguments
420 /// that are passed through the stack.
421 struct AVRFrameAnalyzer : public MachineFunctionPass {
422   static char ID;
423   AVRFrameAnalyzer() : MachineFunctionPass(ID) {}
424 
425   bool runOnMachineFunction(MachineFunction &MF) {
426     const MachineFrameInfo &MFI = MF.getFrameInfo();
427     AVRMachineFunctionInfo *FuncInfo = MF.getInfo<AVRMachineFunctionInfo>();
428 
429     // If there are no fixed frame indexes during this stage it means there
430     // are allocas present in the function.
431     if (MFI.getNumObjects() != MFI.getNumFixedObjects()) {
432       // Check for the type of allocas present in the function. We only care
433       // about fixed size allocas so do not give false positives if only
434       // variable sized allocas are present.
435       for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
436         // Variable sized objects have size 0.
437         if (MFI.getObjectSize(i)) {
438           FuncInfo->setHasAllocas(true);
439           break;
440         }
441       }
442     }
443 
444     // If there are fixed frame indexes present, scan the function to see if
445     // they are really being used.
446     if (MFI.getNumFixedObjects() == 0) {
447       return false;
448     }
449 
450     // Ok fixed frame indexes present, now scan the function to see if they
451     // are really being used, otherwise we can ignore them.
452     for (const MachineBasicBlock &BB : MF) {
453       for (const MachineInstr &MI : BB) {
454         int Opcode = MI.getOpcode();
455 
456         if ((Opcode != AVR::LDDRdPtrQ) && (Opcode != AVR::LDDWRdPtrQ) &&
457             (Opcode != AVR::STDPtrQRr) && (Opcode != AVR::STDWPtrQRr)) {
458           continue;
459         }
460 
461         for (const MachineOperand &MO : MI.operands()) {
462           if (!MO.isFI()) {
463             continue;
464           }
465 
466           if (MFI.isFixedObjectIndex(MO.getIndex())) {
467             FuncInfo->setHasStackArgs(true);
468             return false;
469           }
470         }
471       }
472     }
473 
474     return false;
475   }
476 
477   StringRef getPassName() const { return "AVR Frame Analyzer"; }
478 };
479 
480 char AVRFrameAnalyzer::ID = 0;
481 
482 /// Creates instance of the frame analyzer pass.
483 FunctionPass *createAVRFrameAnalyzerPass() { return new AVRFrameAnalyzer(); }
484 
485 /// Create the Dynalloca Stack Pointer Save/Restore pass.
486 /// Insert a copy of SP before allocating the dynamic stack memory and restore
487 /// it in function exit to restore the original SP state. This avoids the need
488 /// of reserving a register pair for a frame pointer.
489 struct AVRDynAllocaSR : public MachineFunctionPass {
490   static char ID;
491   AVRDynAllocaSR() : MachineFunctionPass(ID) {}
492 
493   bool runOnMachineFunction(MachineFunction &MF) {
494     // Early exit when there are no variable sized objects in the function.
495     if (!MF.getFrameInfo().hasVarSizedObjects()) {
496       return false;
497     }
498 
499     const AVRSubtarget &STI = MF.getSubtarget<AVRSubtarget>();
500     const TargetInstrInfo &TII = *STI.getInstrInfo();
501     MachineBasicBlock &EntryMBB = MF.front();
502     MachineBasicBlock::iterator MBBI = EntryMBB.begin();
503     DebugLoc DL = EntryMBB.findDebugLoc(MBBI);
504 
505     Register SPCopy =
506         MF.getRegInfo().createVirtualRegister(&AVR::DREGSRegClass);
507 
508     // Create a copy of SP in function entry before any dynallocas are
509     // inserted.
510     BuildMI(EntryMBB, MBBI, DL, TII.get(AVR::COPY), SPCopy).addReg(AVR::SP);
511 
512     // Restore SP in all exit basic blocks.
513     for (MachineBasicBlock &MBB : MF) {
514       // If last instruction is a return instruction, add a restore copy.
515       if (!MBB.empty() && MBB.back().isReturn()) {
516         MBBI = MBB.getLastNonDebugInstr();
517         DL = MBBI->getDebugLoc();
518         BuildMI(MBB, MBBI, DL, TII.get(AVR::COPY), AVR::SP)
519             .addReg(SPCopy, RegState::Kill);
520       }
521     }
522 
523     return true;
524   }
525 
526   StringRef getPassName() const {
527     return "AVR dynalloca stack pointer save/restore";
528   }
529 };
530 
531 char AVRDynAllocaSR::ID = 0;
532 
533 /// createAVRDynAllocaSRPass - returns an instance of the dynalloca stack
534 /// pointer save/restore pass.
535 FunctionPass *createAVRDynAllocaSRPass() { return new AVRDynAllocaSR(); }
536 
537 } // end of namespace llvm
538 
539