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