1 //===-- XCoreFrameLowering.cpp - Frame info for XCore Target --------------===//
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 XCore frame information that doesn't fit anywhere else
11 // cleanly...
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "XCoreFrameLowering.h"
16 #include "XCore.h"
17 #include "XCoreInstrInfo.h"
18 #include "XCoreMachineFunctionInfo.h"
19 #include "XCoreSubtarget.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/RegisterScavenging.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include <algorithm>    // std::sort
32 
33 using namespace llvm;
34 
35 static const unsigned FramePtr = XCore::R10;
36 static const int MaxImmU16 = (1<<16) - 1;
37 
38 // helper functions. FIXME: Eliminate.
isImmU6(unsigned val)39 static inline bool isImmU6(unsigned val) {
40   return val < (1 << 6);
41 }
42 
isImmU16(unsigned val)43 static inline bool isImmU16(unsigned val) {
44   return val < (1 << 16);
45 }
46 
47 // Helper structure with compare function for handling stack slots.
48 namespace {
49 struct StackSlotInfo {
50   int FI;
51   int Offset;
52   unsigned Reg;
StackSlotInfo__anonae6d63eb0111::StackSlotInfo53   StackSlotInfo(int f, int o, int r) : FI(f), Offset(o), Reg(r){};
54 };
55 }  // end anonymous namespace
56 
CompareSSIOffset(const StackSlotInfo & a,const StackSlotInfo & b)57 static bool CompareSSIOffset(const StackSlotInfo& a, const StackSlotInfo& b) {
58   return a.Offset < b.Offset;
59 }
60 
61 
EmitDefCfaRegister(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,DebugLoc dl,const TargetInstrInfo & TII,MachineModuleInfo * MMI,unsigned DRegNum)62 static void EmitDefCfaRegister(MachineBasicBlock &MBB,
63                                MachineBasicBlock::iterator MBBI, DebugLoc dl,
64                                const TargetInstrInfo &TII,
65                                MachineModuleInfo *MMI, unsigned DRegNum) {
66   unsigned CFIIndex = MMI->addFrameInst(
67       MCCFIInstruction::createDefCfaRegister(nullptr, DRegNum));
68   BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
69       .addCFIIndex(CFIIndex);
70 }
71 
EmitDefCfaOffset(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,DebugLoc dl,const TargetInstrInfo & TII,MachineModuleInfo * MMI,int Offset)72 static void EmitDefCfaOffset(MachineBasicBlock &MBB,
73                              MachineBasicBlock::iterator MBBI, DebugLoc dl,
74                              const TargetInstrInfo &TII,
75                              MachineModuleInfo *MMI, int Offset) {
76   unsigned CFIIndex =
77       MMI->addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -Offset));
78   BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
79       .addCFIIndex(CFIIndex);
80 }
81 
EmitCfiOffset(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,DebugLoc dl,const TargetInstrInfo & TII,MachineModuleInfo * MMI,unsigned DRegNum,int Offset)82 static void EmitCfiOffset(MachineBasicBlock &MBB,
83                           MachineBasicBlock::iterator MBBI, DebugLoc dl,
84                           const TargetInstrInfo &TII, MachineModuleInfo *MMI,
85                           unsigned DRegNum, int Offset) {
86   unsigned CFIIndex = MMI->addFrameInst(
87       MCCFIInstruction::createOffset(nullptr, DRegNum, Offset));
88   BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
89       .addCFIIndex(CFIIndex);
90 }
91 
92 /// The SP register is moved in steps of 'MaxImmU16' towards the bottom of the
93 /// frame. During these steps, it may be necessary to spill registers.
94 /// IfNeededExtSP emits the necessary EXTSP instructions to move the SP only
95 /// as far as to make 'OffsetFromBottom' reachable using an STWSP_lru6.
96 /// \param OffsetFromTop the spill offset from the top of the frame.
97 /// \param [in,out] Adjusted the current SP offset from the top of the frame.
IfNeededExtSP(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,DebugLoc dl,const TargetInstrInfo & TII,MachineModuleInfo * MMI,int OffsetFromTop,int & Adjusted,int FrameSize,bool emitFrameMoves)98 static void IfNeededExtSP(MachineBasicBlock &MBB,
99                           MachineBasicBlock::iterator MBBI, DebugLoc dl,
100                           const TargetInstrInfo &TII, MachineModuleInfo *MMI,
101                           int OffsetFromTop, int &Adjusted, int FrameSize,
102                           bool emitFrameMoves) {
103   while (OffsetFromTop > Adjusted) {
104     assert(Adjusted < FrameSize && "OffsetFromTop is beyond FrameSize");
105     int remaining = FrameSize - Adjusted;
106     int OpImm = (remaining > MaxImmU16) ? MaxImmU16 : remaining;
107     int Opcode = isImmU6(OpImm) ? XCore::EXTSP_u6 : XCore::EXTSP_lu6;
108     BuildMI(MBB, MBBI, dl, TII.get(Opcode)).addImm(OpImm);
109     Adjusted += OpImm;
110     if (emitFrameMoves)
111       EmitDefCfaOffset(MBB, MBBI, dl, TII, MMI, Adjusted*4);
112   }
113 }
114 
115 /// The SP register is moved in steps of 'MaxImmU16' towards the top of the
116 /// frame. During these steps, it may be necessary to re-load registers.
117 /// IfNeededLDAWSP emits the necessary LDAWSP instructions to move the SP only
118 /// as far as to make 'OffsetFromTop' reachable using an LDAWSP_lru6.
119 /// \param OffsetFromTop the spill offset from the top of the frame.
120 /// \param [in,out] RemainingAdj the current SP offset from the top of the
121 /// frame.
IfNeededLDAWSP(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,DebugLoc dl,const TargetInstrInfo & TII,int OffsetFromTop,int & RemainingAdj)122 static void IfNeededLDAWSP(MachineBasicBlock &MBB,
123                            MachineBasicBlock::iterator MBBI, DebugLoc dl,
124                            const TargetInstrInfo &TII, int OffsetFromTop,
125                            int &RemainingAdj) {
126   while (OffsetFromTop < RemainingAdj - MaxImmU16) {
127     assert(RemainingAdj && "OffsetFromTop is beyond FrameSize");
128     int OpImm = (RemainingAdj > MaxImmU16) ? MaxImmU16 : RemainingAdj;
129     int Opcode = isImmU6(OpImm) ? XCore::LDAWSP_ru6 : XCore::LDAWSP_lru6;
130     BuildMI(MBB, MBBI, dl, TII.get(Opcode), XCore::SP).addImm(OpImm);
131     RemainingAdj -= OpImm;
132   }
133 }
134 
135 /// Creates an ordered list of registers that are spilled
136 /// during the emitPrologue/emitEpilogue.
137 /// Registers are ordered according to their frame offset.
138 /// As offsets are negative, the largest offsets will be first.
GetSpillList(SmallVectorImpl<StackSlotInfo> & SpillList,MachineFrameInfo * MFI,XCoreFunctionInfo * XFI,bool fetchLR,bool fetchFP)139 static void GetSpillList(SmallVectorImpl<StackSlotInfo> &SpillList,
140                          MachineFrameInfo *MFI, XCoreFunctionInfo *XFI,
141                          bool fetchLR, bool fetchFP) {
142   if (fetchLR) {
143     int Offset = MFI->getObjectOffset(XFI->getLRSpillSlot());
144     SpillList.push_back(StackSlotInfo(XFI->getLRSpillSlot(),
145                                       Offset,
146                                       XCore::LR));
147   }
148   if (fetchFP) {
149     int Offset = MFI->getObjectOffset(XFI->getFPSpillSlot());
150     SpillList.push_back(StackSlotInfo(XFI->getFPSpillSlot(),
151                                       Offset,
152                                       FramePtr));
153   }
154   std::sort(SpillList.begin(), SpillList.end(), CompareSSIOffset);
155 }
156 
157 /// Creates an ordered list of EH info register 'spills'.
158 /// These slots are only used by the unwinder and calls to llvm.eh.return().
159 /// Registers are ordered according to their frame offset.
160 /// As offsets are negative, the largest offsets will be first.
GetEHSpillList(SmallVectorImpl<StackSlotInfo> & SpillList,MachineFrameInfo * MFI,XCoreFunctionInfo * XFI,const TargetLowering * TL)161 static void GetEHSpillList(SmallVectorImpl<StackSlotInfo> &SpillList,
162                            MachineFrameInfo *MFI, XCoreFunctionInfo *XFI,
163                            const TargetLowering *TL) {
164   assert(XFI->hasEHSpillSlot() && "There are no EH register spill slots");
165   const int* EHSlot = XFI->getEHSpillSlot();
166   SpillList.push_back(StackSlotInfo(EHSlot[0],
167                                     MFI->getObjectOffset(EHSlot[0]),
168                                     TL->getExceptionPointerRegister()));
169   SpillList.push_back(StackSlotInfo(EHSlot[0],
170                                     MFI->getObjectOffset(EHSlot[1]),
171                                     TL->getExceptionSelectorRegister()));
172   std::sort(SpillList.begin(), SpillList.end(), CompareSSIOffset);
173 }
174 
175 
176 static MachineMemOperand *
getFrameIndexMMO(MachineBasicBlock & MBB,int FrameIndex,unsigned flags)177 getFrameIndexMMO(MachineBasicBlock &MBB, int FrameIndex, unsigned flags) {
178   MachineFunction *MF = MBB.getParent();
179   const MachineFrameInfo &MFI = *MF->getFrameInfo();
180   MachineMemOperand *MMO =
181     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIndex),
182                              flags, MFI.getObjectSize(FrameIndex),
183                              MFI.getObjectAlignment(FrameIndex));
184   return MMO;
185 }
186 
187 
188 /// Restore clobbered registers with their spill slot value.
189 /// The SP will be adjusted at the same time, thus the SpillList must be ordered
190 /// with the largest (negative) offsets first.
191 static void
RestoreSpillList(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,DebugLoc dl,const TargetInstrInfo & TII,int & RemainingAdj,SmallVectorImpl<StackSlotInfo> & SpillList)192 RestoreSpillList(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
193                  DebugLoc dl, const TargetInstrInfo &TII, int &RemainingAdj,
194                  SmallVectorImpl<StackSlotInfo> &SpillList) {
195   for (unsigned i = 0, e = SpillList.size(); i != e; ++i) {
196     assert(SpillList[i].Offset % 4 == 0 && "Misaligned stack offset");
197     assert(SpillList[i].Offset <= 0 && "Unexpected positive stack offset");
198     int OffsetFromTop = - SpillList[i].Offset/4;
199     IfNeededLDAWSP(MBB, MBBI, dl, TII, OffsetFromTop, RemainingAdj);
200     int Offset = RemainingAdj - OffsetFromTop;
201     int Opcode = isImmU6(Offset) ? XCore::LDWSP_ru6 : XCore::LDWSP_lru6;
202     BuildMI(MBB, MBBI, dl, TII.get(Opcode), SpillList[i].Reg)
203       .addImm(Offset)
204       .addMemOperand(getFrameIndexMMO(MBB, SpillList[i].FI,
205                                       MachineMemOperand::MOLoad));
206   }
207 }
208 
209 //===----------------------------------------------------------------------===//
210 // XCoreFrameLowering:
211 //===----------------------------------------------------------------------===//
212 
XCoreFrameLowering(const XCoreSubtarget & sti)213 XCoreFrameLowering::XCoreFrameLowering(const XCoreSubtarget &sti)
214   : TargetFrameLowering(TargetFrameLowering::StackGrowsDown, 4, 0) {
215   // Do nothing
216 }
217 
hasFP(const MachineFunction & MF) const218 bool XCoreFrameLowering::hasFP(const MachineFunction &MF) const {
219   return MF.getTarget().Options.DisableFramePointerElim(MF) ||
220          MF.getFrameInfo()->hasVarSizedObjects();
221 }
222 
emitPrologue(MachineFunction & MF) const223 void XCoreFrameLowering::emitPrologue(MachineFunction &MF) const {
224   MachineBasicBlock &MBB = MF.front();   // Prolog goes in entry BB
225   MachineBasicBlock::iterator MBBI = MBB.begin();
226   MachineFrameInfo *MFI = MF.getFrameInfo();
227   MachineModuleInfo *MMI = &MF.getMMI();
228   const MCRegisterInfo *MRI = MMI->getContext().getRegisterInfo();
229   const XCoreInstrInfo &TII = *MF.getSubtarget<XCoreSubtarget>().getInstrInfo();
230   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
231   // Debug location must be unknown since the first debug location is used
232   // to determine the end of the prologue.
233   DebugLoc dl;
234 
235   if (MFI->getMaxAlignment() > getStackAlignment())
236     report_fatal_error("emitPrologue unsupported alignment: "
237                        + Twine(MFI->getMaxAlignment()));
238 
239   const AttributeSet &PAL = MF.getFunction()->getAttributes();
240   if (PAL.hasAttrSomewhere(Attribute::Nest))
241     BuildMI(MBB, MBBI, dl, TII.get(XCore::LDWSP_ru6), XCore::R11).addImm(0);
242     // FIX: Needs addMemOperand() but can't use getFixedStack() or getStack().
243 
244   // Work out frame sizes.
245   // We will adjust the SP in stages towards the final FrameSize.
246   assert(MFI->getStackSize()%4 == 0 && "Misaligned frame size");
247   const int FrameSize = MFI->getStackSize() / 4;
248   int Adjusted = 0;
249 
250   bool saveLR = XFI->hasLRSpillSlot();
251   bool UseENTSP = saveLR && FrameSize
252                   && (MFI->getObjectOffset(XFI->getLRSpillSlot()) == 0);
253   if (UseENTSP)
254     saveLR = false;
255   bool FP = hasFP(MF);
256   bool emitFrameMoves = XCoreRegisterInfo::needsFrameMoves(MF);
257 
258   if (UseENTSP) {
259     // Allocate space on the stack at the same time as saving LR.
260     Adjusted = (FrameSize > MaxImmU16) ? MaxImmU16 : FrameSize;
261     int Opcode = isImmU6(Adjusted) ? XCore::ENTSP_u6 : XCore::ENTSP_lu6;
262     MBB.addLiveIn(XCore::LR);
263     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(Opcode));
264     MIB.addImm(Adjusted);
265     MIB->addRegisterKilled(XCore::LR, MF.getSubtarget().getRegisterInfo(),
266                            true);
267     if (emitFrameMoves) {
268       EmitDefCfaOffset(MBB, MBBI, dl, TII, MMI, Adjusted*4);
269       unsigned DRegNum = MRI->getDwarfRegNum(XCore::LR, true);
270       EmitCfiOffset(MBB, MBBI, dl, TII, MMI, DRegNum, 0);
271     }
272   }
273 
274   // If necessary, save LR and FP to the stack, as we EXTSP.
275   SmallVector<StackSlotInfo,2> SpillList;
276   GetSpillList(SpillList, MFI, XFI, saveLR, FP);
277   // We want the nearest (negative) offsets first, so reverse list.
278   std::reverse(SpillList.begin(), SpillList.end());
279   for (unsigned i = 0, e = SpillList.size(); i != e; ++i) {
280     assert(SpillList[i].Offset % 4 == 0 && "Misaligned stack offset");
281     assert(SpillList[i].Offset <= 0 && "Unexpected positive stack offset");
282     int OffsetFromTop = - SpillList[i].Offset/4;
283     IfNeededExtSP(MBB, MBBI, dl, TII, MMI, OffsetFromTop, Adjusted, FrameSize,
284                   emitFrameMoves);
285     int Offset = Adjusted - OffsetFromTop;
286     int Opcode = isImmU6(Offset) ? XCore::STWSP_ru6 : XCore::STWSP_lru6;
287     MBB.addLiveIn(SpillList[i].Reg);
288     BuildMI(MBB, MBBI, dl, TII.get(Opcode))
289       .addReg(SpillList[i].Reg, RegState::Kill)
290       .addImm(Offset)
291       .addMemOperand(getFrameIndexMMO(MBB, SpillList[i].FI,
292                                       MachineMemOperand::MOStore));
293     if (emitFrameMoves) {
294       unsigned DRegNum = MRI->getDwarfRegNum(SpillList[i].Reg, true);
295       EmitCfiOffset(MBB, MBBI, dl, TII, MMI, DRegNum, SpillList[i].Offset);
296     }
297   }
298 
299   // Complete any remaining Stack adjustment.
300   IfNeededExtSP(MBB, MBBI, dl, TII, MMI, FrameSize, Adjusted, FrameSize,
301                 emitFrameMoves);
302   assert(Adjusted==FrameSize && "IfNeededExtSP has not completed adjustment");
303 
304   if (FP) {
305     // Set the FP from the SP.
306     BuildMI(MBB, MBBI, dl, TII.get(XCore::LDAWSP_ru6), FramePtr).addImm(0);
307     if (emitFrameMoves)
308       EmitDefCfaRegister(MBB, MBBI, dl, TII, MMI,
309                          MRI->getDwarfRegNum(FramePtr, true));
310   }
311 
312   if (emitFrameMoves) {
313     // Frame moves for callee saved.
314     for (const auto &SpillLabel : XFI->getSpillLabels()) {
315       MachineBasicBlock::iterator Pos = SpillLabel.first;
316       ++Pos;
317       const CalleeSavedInfo &CSI = SpillLabel.second;
318       int Offset = MFI->getObjectOffset(CSI.getFrameIdx());
319       unsigned DRegNum = MRI->getDwarfRegNum(CSI.getReg(), true);
320       EmitCfiOffset(MBB, Pos, dl, TII, MMI, DRegNum, Offset);
321     }
322     if (XFI->hasEHSpillSlot()) {
323       // The unwinder requires stack slot & CFI offsets for the exception info.
324       // We do not save/spill these registers.
325       SmallVector<StackSlotInfo,2> SpillList;
326       GetEHSpillList(SpillList, MFI, XFI,
327                      MF.getSubtarget().getTargetLowering());
328       assert(SpillList.size()==2 && "Unexpected SpillList size");
329       EmitCfiOffset(MBB, MBBI, dl, TII, MMI,
330                     MRI->getDwarfRegNum(SpillList[0].Reg, true),
331                     SpillList[0].Offset);
332       EmitCfiOffset(MBB, MBBI, dl, TII, MMI,
333                     MRI->getDwarfRegNum(SpillList[1].Reg, true),
334                     SpillList[1].Offset);
335     }
336   }
337 }
338 
emitEpilogue(MachineFunction & MF,MachineBasicBlock & MBB) const339 void XCoreFrameLowering::emitEpilogue(MachineFunction &MF,
340                                      MachineBasicBlock &MBB) const {
341   MachineFrameInfo *MFI = MF.getFrameInfo();
342   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
343   const XCoreInstrInfo &TII = *MF.getSubtarget<XCoreSubtarget>().getInstrInfo();
344   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
345   DebugLoc dl = MBBI->getDebugLoc();
346   unsigned RetOpcode = MBBI->getOpcode();
347 
348   // Work out frame sizes.
349   // We will adjust the SP in stages towards the final FrameSize.
350   int RemainingAdj = MFI->getStackSize();
351   assert(RemainingAdj%4 == 0 && "Misaligned frame size");
352   RemainingAdj /= 4;
353 
354   if (RetOpcode == XCore::EH_RETURN) {
355     // 'Restore' the exception info the unwinder has placed into the stack
356     // slots.
357     SmallVector<StackSlotInfo,2> SpillList;
358     GetEHSpillList(SpillList, MFI, XFI, MF.getSubtarget().getTargetLowering());
359     RestoreSpillList(MBB, MBBI, dl, TII, RemainingAdj, SpillList);
360 
361     // Return to the landing pad.
362     unsigned EhStackReg = MBBI->getOperand(0).getReg();
363     unsigned EhHandlerReg = MBBI->getOperand(1).getReg();
364     BuildMI(MBB, MBBI, dl, TII.get(XCore::SETSP_1r)).addReg(EhStackReg);
365     BuildMI(MBB, MBBI, dl, TII.get(XCore::BAU_1r)).addReg(EhHandlerReg);
366     MBB.erase(MBBI);  // Erase the previous return instruction.
367     return;
368   }
369 
370   bool restoreLR = XFI->hasLRSpillSlot();
371   bool UseRETSP = restoreLR && RemainingAdj
372                   && (MFI->getObjectOffset(XFI->getLRSpillSlot()) == 0);
373   if (UseRETSP)
374     restoreLR = false;
375   bool FP = hasFP(MF);
376 
377   if (FP) // Restore the stack pointer.
378     BuildMI(MBB, MBBI, dl, TII.get(XCore::SETSP_1r)).addReg(FramePtr);
379 
380   // If necessary, restore LR and FP from the stack, as we EXTSP.
381   SmallVector<StackSlotInfo,2> SpillList;
382   GetSpillList(SpillList, MFI, XFI, restoreLR, FP);
383   RestoreSpillList(MBB, MBBI, dl, TII, RemainingAdj, SpillList);
384 
385   if (RemainingAdj) {
386     // Complete all but one of the remaining Stack adjustments.
387     IfNeededLDAWSP(MBB, MBBI, dl, TII, 0, RemainingAdj);
388     if (UseRETSP) {
389       // Fold prologue into return instruction
390       assert(RetOpcode == XCore::RETSP_u6
391              || RetOpcode == XCore::RETSP_lu6);
392       int Opcode = isImmU6(RemainingAdj) ? XCore::RETSP_u6 : XCore::RETSP_lu6;
393       MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(Opcode))
394                                   .addImm(RemainingAdj);
395       for (unsigned i = 3, e = MBBI->getNumOperands(); i < e; ++i)
396         MIB->addOperand(MBBI->getOperand(i)); // copy any variadic operands
397       MBB.erase(MBBI);  // Erase the previous return instruction.
398     } else {
399       int Opcode = isImmU6(RemainingAdj) ? XCore::LDAWSP_ru6 :
400                                            XCore::LDAWSP_lru6;
401       BuildMI(MBB, MBBI, dl, TII.get(Opcode), XCore::SP).addImm(RemainingAdj);
402       // Don't erase the return instruction.
403     }
404   } // else Don't erase the return instruction.
405 }
406 
407 bool XCoreFrameLowering::
spillCalleeSavedRegisters(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,const std::vector<CalleeSavedInfo> & CSI,const TargetRegisterInfo * TRI) const408 spillCalleeSavedRegisters(MachineBasicBlock &MBB,
409                           MachineBasicBlock::iterator MI,
410                           const std::vector<CalleeSavedInfo> &CSI,
411                           const TargetRegisterInfo *TRI) const {
412   if (CSI.empty())
413     return true;
414 
415   MachineFunction *MF = MBB.getParent();
416   const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
417   XCoreFunctionInfo *XFI = MF->getInfo<XCoreFunctionInfo>();
418   bool emitFrameMoves = XCoreRegisterInfo::needsFrameMoves(*MF);
419 
420   DebugLoc DL;
421   if (MI != MBB.end() && !MI->isDebugValue())
422     DL = MI->getDebugLoc();
423 
424   for (std::vector<CalleeSavedInfo>::const_iterator it = CSI.begin();
425                                                     it != CSI.end(); ++it) {
426     unsigned Reg = it->getReg();
427     assert(Reg != XCore::LR && !(Reg == XCore::R10 && hasFP(*MF)) &&
428            "LR & FP are always handled in emitPrologue");
429 
430     // Add the callee-saved register as live-in. It's killed at the spill.
431     MBB.addLiveIn(Reg);
432     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
433     TII.storeRegToStackSlot(MBB, MI, Reg, true, it->getFrameIdx(), RC, TRI);
434     if (emitFrameMoves) {
435       auto Store = MI;
436       --Store;
437       XFI->getSpillLabels().push_back(std::make_pair(Store, *it));
438     }
439   }
440   return true;
441 }
442 
443 bool XCoreFrameLowering::
restoreCalleeSavedRegisters(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,const std::vector<CalleeSavedInfo> & CSI,const TargetRegisterInfo * TRI) const444 restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
445                             MachineBasicBlock::iterator MI,
446                             const std::vector<CalleeSavedInfo> &CSI,
447                             const TargetRegisterInfo *TRI) const{
448   MachineFunction *MF = MBB.getParent();
449   const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
450   bool AtStart = MI == MBB.begin();
451   MachineBasicBlock::iterator BeforeI = MI;
452   if (!AtStart)
453     --BeforeI;
454   for (std::vector<CalleeSavedInfo>::const_iterator it = CSI.begin();
455                                                     it != CSI.end(); ++it) {
456     unsigned Reg = it->getReg();
457     assert(Reg != XCore::LR && !(Reg == XCore::R10 && hasFP(*MF)) &&
458            "LR & FP are always handled in emitEpilogue");
459 
460     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
461     TII.loadRegFromStackSlot(MBB, MI, Reg, it->getFrameIdx(), RC, TRI);
462     assert(MI != MBB.begin() &&
463            "loadRegFromStackSlot didn't insert any code!");
464     // Insert in reverse order.  loadRegFromStackSlot can insert multiple
465     // instructions.
466     if (AtStart)
467       MI = MBB.begin();
468     else {
469       MI = BeforeI;
470       ++MI;
471     }
472   }
473   return true;
474 }
475 
476 // This function eliminates ADJCALLSTACKDOWN,
477 // ADJCALLSTACKUP pseudo instructions
478 void XCoreFrameLowering::
eliminateCallFramePseudoInstr(MachineFunction & MF,MachineBasicBlock & MBB,MachineBasicBlock::iterator I) const479 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
480                               MachineBasicBlock::iterator I) const {
481   const XCoreInstrInfo &TII = *MF.getSubtarget<XCoreSubtarget>().getInstrInfo();
482   if (!hasReservedCallFrame(MF)) {
483     // Turn the adjcallstackdown instruction into 'extsp <amt>' and the
484     // adjcallstackup instruction into 'ldaw sp, sp[<amt>]'
485     MachineInstr *Old = I;
486     uint64_t Amount = Old->getOperand(0).getImm();
487     if (Amount != 0) {
488       // We need to keep the stack aligned properly.  To do this, we round the
489       // amount of space needed for the outgoing arguments up to the next
490       // alignment boundary.
491       unsigned Align = getStackAlignment();
492       Amount = (Amount+Align-1)/Align*Align;
493 
494       assert(Amount%4 == 0);
495       Amount /= 4;
496 
497       bool isU6 = isImmU6(Amount);
498       if (!isU6 && !isImmU16(Amount)) {
499         // FIX could emit multiple instructions in this case.
500 #ifndef NDEBUG
501         errs() << "eliminateCallFramePseudoInstr size too big: "
502                << Amount << "\n";
503 #endif
504         llvm_unreachable(nullptr);
505       }
506 
507       MachineInstr *New;
508       if (Old->getOpcode() == XCore::ADJCALLSTACKDOWN) {
509         int Opcode = isU6 ? XCore::EXTSP_u6 : XCore::EXTSP_lu6;
510         New=BuildMI(MF, Old->getDebugLoc(), TII.get(Opcode))
511           .addImm(Amount);
512       } else {
513         assert(Old->getOpcode() == XCore::ADJCALLSTACKUP);
514         int Opcode = isU6 ? XCore::LDAWSP_ru6 : XCore::LDAWSP_lru6;
515         New=BuildMI(MF, Old->getDebugLoc(), TII.get(Opcode), XCore::SP)
516           .addImm(Amount);
517       }
518 
519       // Replace the pseudo instruction with a new instruction...
520       MBB.insert(I, New);
521     }
522   }
523 
524   MBB.erase(I);
525 }
526 
527 void XCoreFrameLowering::
processFunctionBeforeCalleeSavedScan(MachineFunction & MF,RegScavenger * RS) const528 processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
529                                      RegScavenger *RS) const {
530   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
531 
532   bool LRUsed = MF.getRegInfo().isPhysRegUsed(XCore::LR);
533 
534   if (!LRUsed && !MF.getFunction()->isVarArg() &&
535       MF.getFrameInfo()->estimateStackSize(MF))
536     // If we need to extend the stack it is more efficient to use entsp / retsp.
537     // We force the LR to be saved so these instructions are used.
538     LRUsed = true;
539 
540   if (MF.getMMI().callsUnwindInit() || MF.getMMI().callsEHReturn()) {
541     // The unwinder expects to find spill slots for the exception info regs R0
542     // & R1. These are used during llvm.eh.return() to 'restore' the exception
543     // info. N.B. we do not spill or restore R0, R1 during normal operation.
544     XFI->createEHSpillSlot(MF);
545     // As we will  have a stack, we force the LR to be saved.
546     LRUsed = true;
547   }
548 
549   if (LRUsed) {
550     // We will handle the LR in the prologue/epilogue
551     // and allocate space on the stack ourselves.
552     MF.getRegInfo().setPhysRegUnused(XCore::LR);
553     XFI->createLRSpillSlot(MF);
554   }
555 
556   if (hasFP(MF))
557     // A callee save register is used to hold the FP.
558     // This needs saving / restoring in the epilogue / prologue.
559     XFI->createFPSpillSlot(MF);
560 }
561 
562 void XCoreFrameLowering::
processFunctionBeforeFrameFinalized(MachineFunction & MF,RegScavenger * RS) const563 processFunctionBeforeFrameFinalized(MachineFunction &MF,
564                                     RegScavenger *RS) const {
565   assert(RS && "requiresRegisterScavenging failed");
566   MachineFrameInfo *MFI = MF.getFrameInfo();
567   const TargetRegisterClass *RC = &XCore::GRRegsRegClass;
568   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
569   // Reserve slots close to SP or frame pointer for Scavenging spills.
570   // When using SP for small frames, we don't need any scratch registers.
571   // When using SP for large frames, we may need 2 scratch registers.
572   // When using FP, for large or small frames, we may need 1 scratch register.
573   if (XFI->isLargeFrame(MF) || hasFP(MF))
574     RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
575                                                        RC->getAlignment(),
576                                                        false));
577   if (XFI->isLargeFrame(MF) && !hasFP(MF))
578     RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
579                                                        RC->getAlignment(),
580                                                        false));
581 }
582