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 "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/RegisterScavenging.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Target/TargetOptions.h"
29 
30 using namespace llvm;
31 
32 // helper functions. FIXME: Eliminate.
33 static inline bool isImmUs(unsigned val) {
34   return val <= 11;
35 }
36 
37 static inline bool isImmU6(unsigned val) {
38   return val < (1 << 6);
39 }
40 
41 static inline bool isImmU16(unsigned val) {
42   return val < (1 << 16);
43 }
44 
45 static void loadFromStack(MachineBasicBlock &MBB,
46                           MachineBasicBlock::iterator I,
47                           unsigned DstReg, int Offset, DebugLoc dl,
48                           const TargetInstrInfo &TII) {
49   assert(Offset%4 == 0 && "Misaligned stack offset");
50   Offset/=4;
51   bool isU6 = isImmU6(Offset);
52   if (!isU6 && !isImmU16(Offset))
53     report_fatal_error("loadFromStack offset too big " + Twine(Offset));
54   int Opcode = isU6 ? XCore::LDWSP_ru6 : XCore::LDWSP_lru6;
55   BuildMI(MBB, I, dl, TII.get(Opcode), DstReg)
56     .addImm(Offset);
57 }
58 
59 
60 static void storeToStack(MachineBasicBlock &MBB,
61                          MachineBasicBlock::iterator I,
62                          unsigned SrcReg, int Offset, DebugLoc dl,
63                          const TargetInstrInfo &TII) {
64   assert(Offset%4 == 0 && "Misaligned stack offset");
65   Offset/=4;
66   bool isU6 = isImmU6(Offset);
67   if (!isU6 && !isImmU16(Offset))
68     report_fatal_error("storeToStack offset too big " + Twine(Offset));
69   int Opcode = isU6 ? XCore::STWSP_ru6 : XCore::STWSP_lru6;
70   BuildMI(MBB, I, dl, TII.get(Opcode))
71     .addReg(SrcReg)
72     .addImm(Offset);
73 }
74 
75 
76 //===----------------------------------------------------------------------===//
77 // XCoreFrameLowering:
78 //===----------------------------------------------------------------------===//
79 
80 XCoreFrameLowering::XCoreFrameLowering(const XCoreSubtarget &sti)
81   : TargetFrameLowering(TargetFrameLowering::StackGrowsDown, 4, 0) {
82   // Do nothing
83 }
84 
85 bool XCoreFrameLowering::hasFP(const MachineFunction &MF) const {
86   return MF.getTarget().Options.DisableFramePointerElim(MF) ||
87     MF.getFrameInfo()->hasVarSizedObjects();
88 }
89 
90 void XCoreFrameLowering::emitPrologue(MachineFunction &MF) const {
91   MachineBasicBlock &MBB = MF.front();   // Prolog goes in entry BB
92   MachineBasicBlock::iterator MBBI = MBB.begin();
93   MachineFrameInfo *MFI = MF.getFrameInfo();
94   MachineModuleInfo *MMI = &MF.getMMI();
95   const XCoreInstrInfo &TII =
96     *static_cast<const XCoreInstrInfo*>(MF.getTarget().getInstrInfo());
97   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
98   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
99 
100   bool FP = hasFP(MF);
101   const AttributeSet &PAL = MF.getFunction()->getAttributes();
102 
103   if (PAL.hasAttrSomewhere(Attribute::Nest))
104     loadFromStack(MBB, MBBI, XCore::R11, 0, dl, TII);
105 
106   // Work out frame sizes.
107   int FrameSize = MFI->getStackSize();
108   assert(FrameSize%4 == 0 && "Misaligned frame size");
109   FrameSize/=4;
110 
111   bool isU6 = isImmU6(FrameSize);
112 
113   if (!isU6 && !isImmU16(FrameSize)) {
114     // FIXME could emit multiple instructions.
115     report_fatal_error("emitPrologue Frame size too big: " + Twine(FrameSize));
116   }
117   bool emitFrameMoves = XCoreRegisterInfo::needsFrameMoves(MF);
118 
119   bool saveLR = XFI->getUsesLR();
120   // Do we need to allocate space on the stack?
121   if (FrameSize) {
122     bool LRSavedOnEntry = false;
123     int Opcode;
124     if (saveLR && (MFI->getObjectOffset(XFI->getLRSpillSlot()) == 0)) {
125       Opcode = (isU6) ? XCore::ENTSP_u6 : XCore::ENTSP_lu6;
126       MBB.addLiveIn(XCore::LR);
127       saveLR = false;
128       LRSavedOnEntry = true;
129     } else {
130       Opcode = (isU6) ? XCore::EXTSP_u6 : XCore::EXTSP_lu6;
131     }
132     BuildMI(MBB, MBBI, dl, TII.get(Opcode)).addImm(FrameSize);
133 
134     if (emitFrameMoves) {
135       std::vector<MachineMove> &Moves = MMI->getFrameMoves();
136 
137       // Show update of SP.
138       MCSymbol *FrameLabel = MMI->getContext().CreateTempSymbol();
139       BuildMI(MBB, MBBI, dl, TII.get(XCore::PROLOG_LABEL)).addSym(FrameLabel);
140 
141       MachineLocation SPDst(MachineLocation::VirtualFP);
142       MachineLocation SPSrc(MachineLocation::VirtualFP, -FrameSize * 4);
143       Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
144 
145       if (LRSavedOnEntry) {
146         MachineLocation CSDst(MachineLocation::VirtualFP, 0);
147         MachineLocation CSSrc(XCore::LR);
148         Moves.push_back(MachineMove(FrameLabel, CSDst, CSSrc));
149       }
150     }
151   }
152   if (saveLR) {
153     int LRSpillOffset = MFI->getObjectOffset(XFI->getLRSpillSlot());
154     storeToStack(MBB, MBBI, XCore::LR, LRSpillOffset + FrameSize*4, dl, TII);
155     MBB.addLiveIn(XCore::LR);
156 
157     if (emitFrameMoves) {
158       MCSymbol *SaveLRLabel = MMI->getContext().CreateTempSymbol();
159       BuildMI(MBB, MBBI, dl, TII.get(XCore::PROLOG_LABEL)).addSym(SaveLRLabel);
160       MachineLocation CSDst(MachineLocation::VirtualFP, LRSpillOffset);
161       MachineLocation CSSrc(XCore::LR);
162       MMI->getFrameMoves().push_back(MachineMove(SaveLRLabel, CSDst, CSSrc));
163     }
164   }
165 
166   if (FP) {
167     // Save R10 to the stack.
168     int FPSpillOffset = MFI->getObjectOffset(XFI->getFPSpillSlot());
169     storeToStack(MBB, MBBI, XCore::R10, FPSpillOffset + FrameSize*4, dl, TII);
170     // R10 is live-in. It is killed at the spill.
171     MBB.addLiveIn(XCore::R10);
172     if (emitFrameMoves) {
173       MCSymbol *SaveR10Label = MMI->getContext().CreateTempSymbol();
174       BuildMI(MBB, MBBI, dl, TII.get(XCore::PROLOG_LABEL)).addSym(SaveR10Label);
175       MachineLocation CSDst(MachineLocation::VirtualFP, FPSpillOffset);
176       MachineLocation CSSrc(XCore::R10);
177       MMI->getFrameMoves().push_back(MachineMove(SaveR10Label, CSDst, CSSrc));
178     }
179     // Set the FP from the SP.
180     unsigned FramePtr = XCore::R10;
181     BuildMI(MBB, MBBI, dl, TII.get(XCore::LDAWSP_ru6), FramePtr)
182       .addImm(0);
183     if (emitFrameMoves) {
184       // Show FP is now valid.
185       MCSymbol *FrameLabel = MMI->getContext().CreateTempSymbol();
186       BuildMI(MBB, MBBI, dl, TII.get(XCore::PROLOG_LABEL)).addSym(FrameLabel);
187       MachineLocation SPDst(FramePtr);
188       MachineLocation SPSrc(MachineLocation::VirtualFP);
189       MMI->getFrameMoves().push_back(MachineMove(FrameLabel, SPDst, SPSrc));
190     }
191   }
192 
193   if (emitFrameMoves) {
194     // Frame moves for callee saved.
195     std::vector<MachineMove> &Moves = MMI->getFrameMoves();
196     std::vector<std::pair<MCSymbol*, CalleeSavedInfo> >&SpillLabels =
197         XFI->getSpillLabels();
198     for (unsigned I = 0, E = SpillLabels.size(); I != E; ++I) {
199       MCSymbol *SpillLabel = SpillLabels[I].first;
200       CalleeSavedInfo &CSI = SpillLabels[I].second;
201       int Offset = MFI->getObjectOffset(CSI.getFrameIdx());
202       unsigned Reg = CSI.getReg();
203       MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
204       MachineLocation CSSrc(Reg);
205       Moves.push_back(MachineMove(SpillLabel, CSDst, CSSrc));
206     }
207   }
208 }
209 
210 void XCoreFrameLowering::emitEpilogue(MachineFunction &MF,
211                                      MachineBasicBlock &MBB) const {
212   MachineFrameInfo *MFI            = MF.getFrameInfo();
213   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
214   const XCoreInstrInfo &TII =
215     *static_cast<const XCoreInstrInfo*>(MF.getTarget().getInstrInfo());
216   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
217   DebugLoc dl = MBBI->getDebugLoc();
218 
219   bool FP = hasFP(MF);
220   if (FP) {
221     // Restore the stack pointer.
222     unsigned FramePtr = XCore::R10;
223     BuildMI(MBB, MBBI, dl, TII.get(XCore::SETSP_1r))
224       .addReg(FramePtr);
225   }
226 
227   // Work out frame sizes.
228   int FrameSize = MFI->getStackSize();
229 
230   assert(FrameSize%4 == 0 && "Misaligned frame size");
231 
232   FrameSize/=4;
233 
234   bool isU6 = isImmU6(FrameSize);
235 
236   if (!isU6 && !isImmU16(FrameSize)) {
237     // FIXME could emit multiple instructions.
238     report_fatal_error("emitEpilogue Frame size too big: " + Twine(FrameSize));
239   }
240 
241   if (FP) {
242     // Restore R10
243     int FPSpillOffset = MFI->getObjectOffset(XFI->getFPSpillSlot());
244     FPSpillOffset += FrameSize*4;
245     loadFromStack(MBB, MBBI, XCore::R10, FPSpillOffset, dl, TII);
246   }
247 
248   bool restoreLR = XFI->getUsesLR();
249   if (restoreLR &&
250       (FrameSize == 0 || MFI->getObjectOffset(XFI->getLRSpillSlot()) != 0)) {
251     int LRSpillOffset = MFI->getObjectOffset(XFI->getLRSpillSlot());
252     LRSpillOffset += FrameSize*4;
253     loadFromStack(MBB, MBBI, XCore::LR, LRSpillOffset, dl, TII);
254     restoreLR = false;
255   }
256 
257   if (FrameSize) {
258     if (restoreLR) {
259       // Fold prologue into return instruction
260       assert(MFI->getObjectOffset(XFI->getLRSpillSlot()) == 0);
261       assert(MBBI->getOpcode() == XCore::RETSP_u6
262         || MBBI->getOpcode() == XCore::RETSP_lu6);
263       int Opcode = (isU6) ? XCore::RETSP_u6 : XCore::RETSP_lu6;
264       BuildMI(MBB, MBBI, dl, TII.get(Opcode)).addImm(FrameSize);
265       MBB.erase(MBBI);
266     } else {
267       int Opcode = (isU6) ? XCore::LDAWSP_ru6 : XCore::LDAWSP_lru6;
268       BuildMI(MBB, MBBI, dl, TII.get(Opcode), XCore::SP).addImm(FrameSize);
269     }
270   }
271 }
272 
273 bool XCoreFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
274                                                MachineBasicBlock::iterator MI,
275                                         const std::vector<CalleeSavedInfo> &CSI,
276                                           const TargetRegisterInfo *TRI) const {
277   if (CSI.empty())
278     return true;
279 
280   MachineFunction *MF = MBB.getParent();
281   const TargetInstrInfo &TII = *MF->getTarget().getInstrInfo();
282 
283   XCoreFunctionInfo *XFI = MF->getInfo<XCoreFunctionInfo>();
284   bool emitFrameMoves = XCoreRegisterInfo::needsFrameMoves(*MF);
285 
286   DebugLoc DL;
287   if (MI != MBB.end()) DL = MI->getDebugLoc();
288 
289   for (std::vector<CalleeSavedInfo>::const_iterator it = CSI.begin();
290                                                     it != CSI.end(); ++it) {
291     // Add the callee-saved register as live-in. It's killed at the spill.
292     MBB.addLiveIn(it->getReg());
293 
294     unsigned Reg = it->getReg();
295     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
296     TII.storeRegToStackSlot(MBB, MI, Reg, true,
297                             it->getFrameIdx(), RC, TRI);
298     if (emitFrameMoves) {
299       MCSymbol *SaveLabel = MF->getContext().CreateTempSymbol();
300       BuildMI(MBB, MI, DL, TII.get(XCore::PROLOG_LABEL)).addSym(SaveLabel);
301       XFI->getSpillLabels().push_back(std::make_pair(SaveLabel, *it));
302     }
303   }
304   return true;
305 }
306 
307 bool XCoreFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
308                                                  MachineBasicBlock::iterator MI,
309                                         const std::vector<CalleeSavedInfo> &CSI,
310                                             const TargetRegisterInfo *TRI) const{
311   MachineFunction *MF = MBB.getParent();
312   const TargetInstrInfo &TII = *MF->getTarget().getInstrInfo();
313 
314   bool AtStart = MI == MBB.begin();
315   MachineBasicBlock::iterator BeforeI = MI;
316   if (!AtStart)
317     --BeforeI;
318   for (std::vector<CalleeSavedInfo>::const_iterator it = CSI.begin();
319                                                     it != CSI.end(); ++it) {
320     unsigned Reg = it->getReg();
321     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
322     TII.loadRegFromStackSlot(MBB, MI, it->getReg(), it->getFrameIdx(),
323                              RC, TRI);
324     assert(MI != MBB.begin() &&
325            "loadRegFromStackSlot didn't insert any code!");
326     // Insert in reverse order.  loadRegFromStackSlot can insert multiple
327     // instructions.
328     if (AtStart)
329       MI = MBB.begin();
330     else {
331       MI = BeforeI;
332       ++MI;
333     }
334   }
335   return true;
336 }
337 
338 // This function eliminates ADJCALLSTACKDOWN,
339 // ADJCALLSTACKUP pseudo instructions
340 void XCoreFrameLowering::
341 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
342                               MachineBasicBlock::iterator I) const {
343   const XCoreInstrInfo &TII =
344     *static_cast<const XCoreInstrInfo*>(MF.getTarget().getInstrInfo());
345   if (!hasReservedCallFrame(MF)) {
346     // Turn the adjcallstackdown instruction into 'extsp <amt>' and the
347     // adjcallstackup instruction into 'ldaw sp, sp[<amt>]'
348     MachineInstr *Old = I;
349     uint64_t Amount = Old->getOperand(0).getImm();
350     if (Amount != 0) {
351       // We need to keep the stack aligned properly.  To do this, we round the
352       // amount of space needed for the outgoing arguments up to the next
353       // alignment boundary.
354       unsigned Align = getStackAlignment();
355       Amount = (Amount+Align-1)/Align*Align;
356 
357       assert(Amount%4 == 0);
358       Amount /= 4;
359 
360       bool isU6 = isImmU6(Amount);
361       if (!isU6 && !isImmU16(Amount)) {
362         // FIX could emit multiple instructions in this case.
363 #ifndef NDEBUG
364         errs() << "eliminateCallFramePseudoInstr size too big: "
365                << Amount << "\n";
366 #endif
367         llvm_unreachable(0);
368       }
369 
370       MachineInstr *New;
371       if (Old->getOpcode() == XCore::ADJCALLSTACKDOWN) {
372         int Opcode = isU6 ? XCore::EXTSP_u6 : XCore::EXTSP_lu6;
373         New=BuildMI(MF, Old->getDebugLoc(), TII.get(Opcode))
374           .addImm(Amount);
375       } else {
376         assert(Old->getOpcode() == XCore::ADJCALLSTACKUP);
377         int Opcode = isU6 ? XCore::LDAWSP_ru6 : XCore::LDAWSP_lru6;
378         New=BuildMI(MF, Old->getDebugLoc(), TII.get(Opcode), XCore::SP)
379           .addImm(Amount);
380       }
381 
382       // Replace the pseudo instruction with a new instruction...
383       MBB.insert(I, New);
384     }
385   }
386 
387   MBB.erase(I);
388 }
389 
390 void
391 XCoreFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
392                                                      RegScavenger *RS) const {
393   MachineFrameInfo *MFI = MF.getFrameInfo();
394   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
395   bool LRUsed = MF.getRegInfo().isPhysRegUsed(XCore::LR);
396   const TargetRegisterClass *RC = &XCore::GRRegsRegClass;
397   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
398   if (LRUsed) {
399     MF.getRegInfo().setPhysRegUnused(XCore::LR);
400 
401     bool isVarArg = MF.getFunction()->isVarArg();
402     int FrameIdx;
403     if (! isVarArg) {
404       // A fixed offset of 0 allows us to save / restore LR using entsp / retsp.
405       FrameIdx = MFI->CreateFixedObject(RC->getSize(), 0, true);
406     } else {
407       FrameIdx = MFI->CreateStackObject(RC->getSize(), RC->getAlignment(),
408                                         false);
409     }
410     XFI->setUsesLR(FrameIdx);
411     XFI->setLRSpillSlot(FrameIdx);
412   }
413   if (RegInfo->requiresRegisterScavenging(MF)) {
414     // Reserve a slot close to SP or frame pointer.
415     RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
416                                                        RC->getAlignment(),
417                                                        false));
418   }
419   if (hasFP(MF)) {
420     // A callee save register is used to hold the FP.
421     // This needs saving / restoring in the epilogue / prologue.
422     XFI->setFPSpillSlot(MFI->CreateStackObject(RC->getSize(),
423                                                RC->getAlignment(),
424                                                false));
425   }
426 }
427